validation.ts
12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import moment from "moment";
const normalize = (id) => {
let re;
re = /\[-\/\s]/g;
id = id.toUpperCase().replace(re, "");
re = /\([A-Z0-9]\)$/;
if (re.test(id)) {
id = id.replace(/\[\(\)]/g, "");
}
return id;
};
const isDateValid = (idDate, minDate, maxDate) => {
let isFormatValid, parseDate;
if (minDate == null) {
minDate = "default";
}
if (maxDate == null) {
maxDate = "today";
}
if (minDate === "default" || minDate === "") {
minDate = "18991129";
}
isFormatValid = function (date) {
return typeof date === "string" && /^[0-9]{8}$/.test(date);
};
if (!isFormatValid(idDate)) {
return false;
}
if (!isFormatValid(minDate)) {
return false;
}
parseDate = function (input) {
let date,
day,
isDayValid,
isFutureDate,
isLeapYear,
isMonthValid,
maxDay,
month,
startIndex,
year;
startIndex = 0;
year = +input.substring(startIndex, (startIndex += 4));
month = input.substring(startIndex, (startIndex += 2));
day = +input.substring(startIndex, (startIndex += 2));
date = new Date(year, +month - 1, day);
maxDay =
"01,03,05,07,08,10,12".indexOf(month) >= 0
? 31
: "04,06,09,11".indexOf(month) >= 0
? 30
: ((isLeapYear =
(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0),
isLeapYear ? 29 : 28);
isDayValid = day > 0 && day <= maxDay;
if (!isDayValid) {
return false;
}
isMonthValid = +month > 0 && +month <= 12;
if (!isMonthValid) {
return false;
}
isFutureDate = new Date() < date;
if (isFutureDate) {
return false;
}
return date;
};
idDate = parseDate(idDate);
if (idDate === false) {
return false;
}
minDate = parseDate(minDate);
if (minDate === false) {
return false;
}
maxDate =
maxDate === "today"
? new Date()
: typeof maxDate === "string"
? parseDate(maxDate)
: maxDate;
if (maxDate === false) {
return false;
}
return idDate >= minDate && idDate <= maxDate;
};
const getMaxDate = (yearsOld) => {
let now, year;
now = new Date();
year = now.getFullYear() - yearsOld;
return new Date(year, now.getMonth(), now.getDate());
};
/**
* 身份证校验函数
* @param id
* @returns
*/
export const cnIdCode = (id) => {
let isChecksumValid, isDateValidFn, isFormatValid, isLengthValid
isLengthValid = function (id) {
return id.length === 18
}
isFormatValid = function (id) {
return /^[0-9]{17}[0-9X]$/.test(id)
}
isDateValidFn = function () {
return isDateValid(id.substring(6, 14), '18860625',null)
}
isChecksumValid = function (id) {
let char, checkDigit, getWeight, i, identifier, index, len, remainder, weightedSum
identifier = id.slice(0, -1)
checkDigit = id.slice(-1) === 'X' ? 10 : +id.slice(-1)
getWeight = function (n) {
return Math.pow(2, n - 1) % 11
}
weightedSum = 0
index = id.length
for (i = 0, len = identifier.length; i < len; i++) {
char = identifier[i]
weightedSum += +char * getWeight(index)
index--
}
remainder = (12 - weightedSum % 11) % 11 - checkDigit
return remainder === 0
}
id = normalize(id)
return isLengthValid(id) && isFormatValid(id) && isDateValidFn() && isChecksumValid(id)
};
/**
* 校验工具类
*/
export class StringUtils {
constructor() {
}
/**
* 判断是空字符串?
* @param str
*/
static isBlank(str: string) {
return str === undefined || str === null || '' === str.trim();
}
/**
* 去空格
* @param str 处理字符串
* @return 结果字符串
*/
static trim(str: string) {
return str.replace('\n', '').replace(' ', '').trim();
}
/**
* 判断不是空字符串?
* @param str
*/
static isNotBlank(str: string) {
return !this.isBlank(str);
}
/**
* 判断是空?
* @param o
*/
static isEmpty(o) {
return o === null || o === 'null' || o === undefined || o === 'undefined' || o === '';
}
/**
* 判断不是空?
* @param o
*/
static isNotEmpty(o) {
return !this.isEmpty(o);
}
/**
* 校验身份证的
* @param code
*/
public static identityCodeValid(code): ProcessResult {
// 判断是否为空 长度是否合法
if (this.isBlank(code) || code.length !== 18) {
return new ProcessResult(false, '身份证长度不够');
}
code = this.trim(code);
// 身份证号格式错误
if (!code || !/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(code)) {
return new ProcessResult(false, '身份证不合法');
}
// 省份对应的省编码
const city = {
11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海',
32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南',
44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西',
62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外'
};
if (!city[code.substr(0, 2)]) {
// 地址编码错误
return new ProcessResult(false, '身份证前2为输入有误');
} else {
// 18位身份证需要验证最后一位校验位
code = code.split('');
// 身份证最后一位
const lastOneCode = code[17];
// 加权因子 ∑(ai×Wi)(mod 11)
const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
// 校验位
const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let sum = 0;
let ai = 0;
let wi = 0;
// 取前17位,(每一位数字 * 每一位数字在加权因子数组的对应的数字) 之和
for (let i = 0; i < 17; i++) {
ai = code[i];
wi = factor[i];
sum += ai * wi;
}
// 算出来的和 mod 11 得到 最后一位,再把传进来的身份证的最后一位和算出来的最后一位对比
return new ProcessResult(parity[sum % 11] === lastOneCode, '身份证不合法');
}
}
/**
* 身份证自定义校验器
*/
public static idCardNoValidator() {
return (control): { [key: string]: any } | null => {
const processResult = this.identityCodeValid(control.value);
return processResult.isSuccess() ? null : {idCardError: {value: control.value, message: processResult.errorMessage}};
};
}
/**
* 统一社会信用代码自定义校验器
*/
public static isValidUSCC() {
return (control): { [key: string]: any } | null => {
const processResult = this.checkUnifiedCreditCode(control.value);
return processResult.isSuccess() ? null : {unifiedCreditCodeError: {value: control.value, message: processResult.errorMessage}};
};
}
/**
* 统一社会信用代码校验
* @param uniCode
*/
public static checkUnifiedCreditCode(uniCode: string): ProcessResult {
// 假如不是18位,错误
if (!uniCode || uniCode.length !== 18) {
return new ProcessResult(false, '统一社会信用代码长度不合法');
}
uniCode = this.trim(uniCode);
// 统一社会信用代码由18位阿拉伯数字或英文大写字母表示(不包括I,O,Z,S,V以防止和阿拉伯字母混淆)-->V:???关我毛事?
const upUniCode = uniCode.toUpperCase();
if (upUniCode.indexOf('I') !== -1 || upUniCode.indexOf('O') !== -1 || upUniCode.indexOf('Z') !== -1 || upUniCode.indexOf('S') !== -1 || upUniCode.indexOf('V') !== -1) {
return new ProcessResult(false, '统一社会信用代码不能含有(I,O,Z,S,V)');
}
// (组织机构代码)校验
const orgCheckCode = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
];
// 组织机构代码加权因子
const orgWeight = [3, 7, 9, 10, 5, 8, 4, 2];
const orgCode = uniCode.substring(8, 17);
let sumOrg = 0;
// 去前8位数 每一位数对应在orgWeight数组的下标 * 对应的加权因子 之和
for (let i = 0; i < 8; i++) {
const tmpAttr = orgCode[i] as any;
const tmpCode = orgCheckCode.indexOf(tmpAttr);
const tmpWeight = orgWeight[i];
sumOrg += (tmpCode * tmpWeight);
}
// 再用11 - 算出的合数 mod 11
const modOrg = 11 - sumOrg % 11;
// 再用算出来的数字转换成最后一位的数字 拿到最后一个字符
const modOrgLast = (modOrg === 10) ? 'X' : ((modOrg === 11) ? '0' : ('' + modOrg));
// 对比算出来的最后一位是否等于给我的组织机构代码的最后一位
if (modOrgLast !== orgCode[8]) {
return new ProcessResult(false, '统一社会信用代码中的组织机构代码不合法');
}
// 最后一位的校验 (A=10, B=11,以此类推)
const uniCheckCode = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
'R', 'T', 'U', 'W', 'X', 'Y'
];
// 统一社会信用代码加权因子
const uniCodeWeight = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
let sumUniCode = 0;
// 去前17位数 每一位数对应在uniCheckCode数组的下标 * 对应的加权因子 之和
for (let i = 0; i < 17; i++) {
const tmpAttr = uniCode[i] as any;
const tmpCode = uniCheckCode.indexOf(tmpAttr);
const tmpWeight = uniCodeWeight[i];
sumUniCode += (tmpCode * tmpWeight);
}
// 再用31 - 算出的合数 mod 31
const modOrgUni = 31 - sumUniCode % 31;
// 在uniCheckCode数组找出对应的字符就是最后一位
const modOrgUniLast = uniCheckCode[modOrgUni % 31];
// 对比算出来的最后一位是否等于给我的信用代码的最后一位
return new ProcessResult(modOrgUniLast + '' === uniCode[17] + '', '统一社会信用代码不合法');
}
/**
* 根据身份证号码获取生日年龄性别
*/
public static getIdCardInformation(idCardNo): IdCardInformation {
const processResult = this.identityCodeValid(idCardNo);
if (processResult.isFailure()) {
return new IdCardInformation(undefined, undefined, undefined);
}
// 区分二代身份证
const mark = idCardNo.length > 15;
// 获取身份证上的出生日期
const birthday = moment(idCardNo.substring(6, mark ? 14 : 11), 'YYYYMMDD').toDate();
// 算出年龄
const age = new Date().getFullYear() - birthday.getFullYear();
// 得出年龄
const gender = !(Number(idCardNo.charAt(mark ? 16 : 14)) % 2 === 0);
// 返回身份证信息
return new IdCardInformation(birthday, age, gender);
}
public static isValidBankCard(cardNumber):ProcessResult {
// 银行卡号长度检查,一般16-19位
if (!/^\d{16,19}$/.test(cardNumber)) {
return new ProcessResult(false, '银行卡号格式/长度不正确');
}
// Luhn算法校验
let sum = 0;
let shouldDouble = false;
for (let i = cardNumber.length - 1; i >= 0; i--) {
let digit = parseInt(cardNumber.charAt(i), 10);
if (shouldDouble) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
shouldDouble = !shouldDouble;
}
return new ProcessResult(sum % 10 === 0, '银行卡号格式不正确');
}
}
/**
* 身份证信息
*/
class IdCardInformation {
/**
* 出生日期
*/
birthday: Date;
/**
* 年龄
*/
age: number;
/**
* 性别
*/
gender: boolean;
constructor(birthday: Date, age: number, gender: boolean) {
this.birthday = birthday;
this.age = age;
this.gender = gender;
}
}
/**
* 处理结果
*/
class ProcessResult {
/**
* 成功?
*/
success: boolean;
/**
* 错误信息
*/
errorMessage: string;
constructor(success: boolean, errorMessage: string) {
this.success = success;
this.errorMessage = errorMessage;
}
/**
* 是成功的?
*/
isSuccess() {
return this.success;
}
/**
* 是失败的?
*/
isFailure() {
return !this.success;
}
}