-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.d.ts
1434 lines (1221 loc) · 42.4 KB
/
validation.d.ts
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { arrayLike } from 'jsc-utils/array';
import { objectAssign, objectEach } from 'jsc-utils/object';
import {
AnyArray,
AnyObject,
isArray,
isBoolean,
isDate,
isError,
isFunction,
isNull,
isNumber,
isObject,
isRegExp,
isString,
isUndefined
} from 'jsc-utils/type';
import {
isDigit,
isEmail,
isFloat,
isIdNo,
isInteger,
isIpV4,
isNumerical,
isPhone,
isUrl
} from 'jsc-utils/validator';
import { stringAssign } from 'jsc-utils/string';
export type AsyncValidatorRuleType =
| 'string'
| 'number'
| 'boolean'
| 'method'
| 'regexp'
| 'integer'
| 'float'
| 'array'
| 'object'
| 'enum'
| 'date'
| 'url'
| 'hex'
| 'email'
| 'any';
export interface AsyncValidatorRuleItem {
trigger?: string;
type?: AsyncValidatorRuleType; // default type is 'string'
required?: boolean;
pattern?: RegExp | string;
min?: number; // Range of type 'string' and 'array'
max?: number; // Range of type 'string' and 'array'
len?: number; // Length of type 'string' and 'array'
enum?: Array<string | number | boolean | null | undefined>; // possible values of type 'enum'
whitespace?: boolean;
fields?: AsyncValidatorRules; // ignore when without required
options?: AnyObject;
defaultField?: { type: AsyncValidatorRuleType }; // 'object' or 'array' containing validation rules
transform?: (value: any) => any;
message?: string;
asyncValidator?: (
rule: AsyncValidatorRuleItem,
value: any,
callback: (error: string | string[] | void) => void,
source: AnyObject,
options: AnyObject
) => void | Promise<void>;
validator?: (
rule: AsyncValidatorRuleItem,
value: any,
callback: (error: string | string[] | void) => void,
source: AnyObject,
options: AnyObject
) => void;
}
export interface AsyncValidatorRules {
[field: string]: AsyncValidatorRuleItem | AsyncValidatorRuleItem[];
}
import Fault from './fault';
type AsyncValidatorTypeMapping = {
[type in AsyncValidatorRuleType]: string;
};
export type ValidationMemberName =
| 'required'
| 'type'
| 'format'
| 'min'
| 'max'
| 'range'
| 'minLength'
| 'maxLength'
| 'length'
| 'flex'
| 'enum'
| 'pattern'
| 'same'
| 'equal'
| 'match'
| 'add';
export const MEMBER_MESSAGES: Record<ValidationMemberName, string> = {
type: '',
format: '',
required: '${field}不能为空',
min: '${field}不能小于 ${limits[0]}',
max: '${field}不能大于 ${limits[0]}',
range: '${field}必须在 ${limits[0]}-${limits[1]} 之间',
minLength: '${field}不能少于 ${limits[0]} 个长度',
maxLength: '${field}不能超过 ${limits[0]} 个长度',
length: '${field}必须是 ${limits[0]} 个长度',
flex: '${field}必须是 ${limits[0]}-${limits[1]} 个长度之间',
enum: '${field}必须是${limits[0].join("、")}之一',
pattern: '${field}不合法',
same: '',
equal: '${field}不正确',
match: '',
add: ''
};
export type ValidationTypeName = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date' | 'method' | 'regExp';
const TYPE_NAME_MAP: Record<ValidationTypeName, string> = {
string: '字符串',
number: '数值',
boolean: '布尔值',
object: '对象',
array: '数组',
date: '日期',
method: '方法',
regExp: '正则'
};
export type ValidationTypeValidator = (value: any) => boolean;
const TYPE_VALIDATORS: Record<ValidationTypeName, ValidationTypeValidator> = {
string: isString,
number: isNumber,
boolean: isBoolean,
object: isObject,
array: isArray,
date: isDate,
method: isFunction,
regExp: isRegExp
};
export type ValidationFormatName =
| 'url'
| 'email'
| 'phone'
| 'ipv4'
| 'idNo'
| 'integer'
| 'float'
| 'numerical'
| 'digit';
const FORMAT_NAME_MAP: Record<ValidationFormatName, string> = {
url: ' URL 地址',
email: '邮箱',
phone: '手机号码',
ipv4: ' IP 地址',
idNo: '身份证号码',
integer: '整数',
float: '浮点数',
numerical: '数值',
digit: '数字'
};
export type ValidationFormatValidator = (value: string) => boolean;
const FORMAT_VALIDATORS: Record<ValidationFormatName, ValidationFormatValidator> = {
url: isUrl,
email: isEmail,
phone: isPhone,
ipv4: isIpV4,
idNo: isIdNo,
integer: isInteger,
float: isFloat,
numerical: isNumerical,
digit: isDigit
};
interface ValidationMsgData extends AnyObject {
type: ValidationMemberName;
field: string;
limits: AnyArray;
}
type ValidationStaticFunc<Return> = (
value: any,
source: AnyObject,
rule: ValidationRule,
schema: ValidationSchema,
msgData: ValidationMsgData
) => Return;
type ValidationDynamicFunc<Return> = Return | ValidationStaticFunc<Return>;
// match
type ValidationAsyncValidator = ValidationStaticFunc<boolean | Promise<boolean>>;
type ValidationMatchReturn = string | boolean | void | Error;
type ValidationMatcher =
| ValidationStaticFunc<ValidationMatchReturn>
| ValidationStaticFunc<Promise<ValidationMatchReturn>>;
// limit
type ValidationLimitFunc<Limit> = (
value: any,
source: AnyObject,
rule: ValidationRule,
schema: ValidationSchema
) => Limit;
export type ValidationLimit<Limit> = Limit | ValidationLimitFunc<Limit>;
type ValidationLimitsFunc<Limits extends AnyArray> = (
value: any,
source: AnyObject,
rule: ValidationRule,
schema: ValidationSchema
) => Limits;
// message
type ValidationMessageFunc = ValidationStaticFunc<string>;
export type ValidationMessage = ValidationDynamicFunc<string>;
// enable
type ValidationEnableFunc = ValidationStaticFunc<boolean>;
export type ValidationEnable = ValidationDynamicFunc<boolean>;
// usable
type ValidationUsableFunc = (value: any, source: AnyObject, schema: ValidationSchema) => boolean;
export type ValidationUsable = boolean | ValidationUsableFunc;
const VALIDATION_FLAG = Symbol('__isValidation__');
export interface ValidationRule {
[VALIDATION_FLAG]: typeof VALIDATION_FLAG;
type: ValidationMemberName;
limits: ValidationLimitsFunc<AnyArray>;
triggers: string[];
message: ValidationMessageFunc;
enable: ValidationEnableFunc;
validator: ValidationAsyncValidator;
}
export type ValidationRules = ValidationRule[];
export interface ValidationDesc {
field: string;
label?: string;
usable: ValidationUsableFunc;
rules: ValidationRules;
[VALIDATION_FLAG]: typeof VALIDATION_FLAG;
}
export interface ValidationSchema {
[field: string]: ValidationDesc;
[VALIDATION_FLAG]: typeof VALIDATION_FLAG;
}
export interface ValidationOptions {
first: boolean;
trigger: string;
fields: string[];
}
export const defaults: Partial<ValidationOptions> = {
first: true,
trigger: undefined,
fields: undefined
};
export type ValidationCallback = (fault: Fault | null, valid: boolean) => void;
const isEmpty = (value: any): boolean => {
if (isUndefined(value) || isNull(value) || value === '') return true;
if (arrayLike(value)) return value.length === 0;
if (isObject(value)) return Object.keys(value).length === 0;
return false;
};
const messageGetter = (
messageFunc: string | ValidationMessageFunc,
message?: ValidationMessage
): ValidationMessageFunc => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
if (isFunction(message)) return message;
if (isString(message)) return (value, source, rule, schema, msgData) => stringAssign(message, msgData);
if (isString(messageFunc)) return (value, source, rule, schema, msgData) => stringAssign(messageFunc, msgData);
return messageFunc;
};
const limitsGetter1 = <Limit1>(limit1: ValidationLimit<Limit1>): ValidationLimitsFunc<[Limit1]> => {
if (isFunction(limit1))
return (value, source, rule, schema) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
[limit1(value, source, rule, schema)];
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
return () => [limit1];
};
const limitsGetter2 = <Limit1, Limit2>(
limit1: ValidationLimit<Limit1>,
limit2: ValidationLimit<Limit2>
): ValidationLimitsFunc<[Limit1, Limit2]> => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
return (value, source, rule, schema) => {
const realLimit1 = isFunction(limit1) ? limit1(value, source, rule, schema) : limit1;
const realLimit2 = isFunction(limit2) ? limit2(value, source, rule, schema) : limit2;
return [realLimit1, realLimit2];
};
};
const matcherToValidator = (matcher: ValidationMatcher): ValidationAsyncValidator => {
return async (value, source, rule, schema, limits): Promise<boolean> => {
const result = await matcher(value, source, rule, schema, limits);
// 返回字符串
if (isString(result)) {
throw new Error(result);
}
// 返回一个错误对象
if (isError(result)) {
throw result;
}
// 返回一个布尔值
if (isBoolean(result)) {
return result;
}
return true;
};
};
const matchSymbol = (obj: any) => {
if (!isObject(obj)) return false;
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
if (obj[VALIDATION_FLAG] === VALIDATION_FLAG) return true;
return Object.getOwnPropertySymbols(obj).some((symbol) => String(symbol) === String(VALIDATION_FLAG));
};
const isValidationRules = (rules: AsyncValidatorRuleItem | AsyncValidatorRuleItem[] | ValidationRules): boolean => {
if (isObject(rules)) return false;
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
if (rules.length === 0) return false;
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
return matchSymbol(rules[0]);
};
const isValidationSchema = (schema: any): schema is ValidationSchema => {
return matchSymbol(schema);
};
const isValidationInstance = (v: any): v is Validation => {
return matchSymbol(v);
};
export default class Validation {
private _currentField?: string;
private _currentLabel?: string;
private _currentRule?: ValidationRule;
private _currentRuleList?: Array<ValidationRule>;
private _currentDesc?: ValidationDesc;
private _fieldList: string[];
private [VALIDATION_FLAG]: typeof VALIDATION_FLAG;
private _schema: ValidationSchema;
// 是否为独立模式,只导出验证规则,没有字段关联
private _standaloneField: string;
constructor() {
this[VALIDATION_FLAG] = VALIDATION_FLAG;
this._schema = {
[VALIDATION_FLAG]: VALIDATION_FLAG
};
this._fieldList = [];
this._standaloneField = '';
}
static create(): Validation {
return new Validation();
}
/**
* 导出所有字段的表单验证模式
* @returns {ValidationSchema}
*/
exportSchema(): ValidationSchema {
return this._schema;
}
/**
* 导入所有字段的验证模式
* @param {ValidationSchema} schema
* @returns {Validation}
*/
importSchema(schema: ValidationSchema): Validation {
this._schema = schema;
this._fieldList = Object.keys(schema);
return this;
}
/**
* 导出指定字段的验证描述
* @param {string} field
* @returns {ValidationDesc}
*/
exportDesc(field: string): ValidationDesc {
const { _schema } = this;
let found: ValidationDesc = { [VALIDATION_FLAG]: VALIDATION_FLAG, field, rules: [], usable: () => true };
objectEach(_schema, (desc, _field) => {
if (_field === field) {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
found = desc;
return false;
}
});
return found;
}
/**
* 获取指定字段的验证规则
* @returns {ValidationRules}
*/
get rules(): ValidationRules {
const { _standaloneField } = this;
if (_standaloneField === '') throw new Error('非独立模式不能获取验证规则');
return this.exportDesc(_standaloneField).rules;
}
/**
* 独立模式,只能导出配置的验证规则
* @returns {Validation}
*/
public standalone(): Validation {
const field = 's';
this._standaloneField = field;
this.field(field);
return this;
}
/**
* 设置验证字段
* @param {string} field
* @returns {Validation}
*/
public field(field: string): Validation {
// console.log(field, 'filed');
this._currentField = field;
// console.log(this._fieldList, '2')
const found = this._fieldList.some((match) => match === field);
if (found) {
this._currentDesc = this._schema[field];
const { _currentDesc } = this;
this._currentRuleList = _currentDesc.rules;
this._currentLabel = _currentDesc.label;
return this;
}
this._currentLabel = undefined;
this._currentRuleList = [];
this._currentDesc = {
[VALIDATION_FLAG]: VALIDATION_FLAG,
field,
rules: this._currentRuleList,
usable: () => true
};
this._schema[field] = this._currentDesc;
this._fieldList.push(field);
// console.log(this._fieldList, '1')
return this;
}
/**
* 设置字段名称
* @param {string} label
* @returns {Validation}
*/
public label(label: string): Validation {
const { _currentDesc } = this;
if (!_currentDesc) throw new Error('必须先指定验证字段');
this._currentLabel = label;
_currentDesc.label = label;
return this;
}
/**
* 寻找验证规则中是否有某个规则
* @param {ValidationMemberName} type
* @returns {boolean}
*/
has(type: ValidationMemberName): boolean {
const { _currentRuleList } = this;
console.log(type, 'type')
if (!_currentRuleList) throw new Error('必须先指定验证字段');
return _currentRuleList.some((rule) => rule.type === type);
}
/**
* 必填验证
* @param {ValidationMessage} message
* @returns {Validation}
*/
public required(message?: ValidationMessage): Validation {
this._createRule('required', {
validator: (value) => !isEmpty(value),
limits: limitsGetter1(true),
message: messageGetter(MEMBER_MESSAGES.required, message)
});
this._pushRule();
console.log(this, 'this')
return this;
}
/**
* 数据类型验证
* @param {ValidationLimit<ValidationTypeName>} type
* @param {ValidationMessage} message
* @returns {Validation}
*/
public type(type: ValidationLimit<ValidationTypeName>, message?: ValidationMessage): Validation {
this._createRule('type', {
validator: (value, source, rule, schema, msgData) => {
if (isUndefined(value) || isNull(value)) return true;
const [type] = msgData.limits;
return TYPE_VALIDATORS[type as ValidationTypeName](value);
},
limits: limitsGetter1(type),
message: messageGetter((value, source, rule, schema, msgData) => {
const type = TYPE_NAME_MAP[msgData.limits[0] as ValidationTypeName];
return stringAssign('${field}必须是' + type + '类型', msgData);
}, message)
});
this._pushRule();
return this;
}
/**
* 数据格式验证
* @param {ValidationLimit<ValidationFormatName>} format
* @param {ValidationMessage} message
* @returns {Validation}
*/
public format(format: ValidationLimit<ValidationFormatName>, message?: ValidationMessage): Validation {
this._createRule('format', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [format] = msgData.limits;
return FORMAT_VALIDATORS[format as ValidationFormatName](value);
},
limits: limitsGetter1<ValidationFormatName>(format),
message: messageGetter((value, source, rule, schema, msgData) => {
const type = FORMAT_NAME_MAP[msgData.limits[0] as ValidationFormatName];
return stringAssign('${field}必须是' + type + '格式', msgData);
}, message)
});
this._pushRule();
return this;
}
/**
* 最小值
* @param {ValidationLimit<number>} min
* @param {ValidationMessage} message
* @returns {Validation}
*/
public min(min: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('min', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [min] = msgData.limits as number[];
return Number(value) >= min;
},
limits: limitsGetter1(min),
message: messageGetter(MEMBER_MESSAGES.min, message)
});
this._pushRule();
return this;
}
/**
* 最大值
* @param {ValidationLimit<number>} max
* @param {ValidationMessage} message
* @returns {Validation}
*/
public max(max: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('max', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [max] = msgData.limits as number[];
return Number(value) <= max;
},
limits: limitsGetter1(max),
message: messageGetter(MEMBER_MESSAGES.max, message)
});
this._pushRule();
return this;
}
/**
* 指定数值范围
* @param {ValidationLimit<number>} min
* @param {ValidationLimit<number>} max
* @param {ValidationMessage} message
* @returns {Validation}
*/
public range(min: ValidationLimit<number>, max: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('range', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [min, max] = msgData.limits as number[];
return value >= min && value <= max;
},
limits: limitsGetter2(min, max),
message: messageGetter(MEMBER_MESSAGES.range, message)
});
this._pushRule();
return this;
}
/**
* 最小长度
* @param {ValidationLimit<number>} minLength
* @param {ValidationMessage} message
* @returns {Validation}
*/
public minLength(minLength: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('minLength', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [minLength] = msgData.limits as number[];
return value.length >= minLength;
},
limits: limitsGetter1(minLength),
message: messageGetter(MEMBER_MESSAGES.minLength, message)
});
this._pushRule();
return this;
}
/**
* 最大长度
* @param {ValidationLimit<number>} maxLength
* @param {ValidationMessage} message
* @returns {Validation}
*/
public maxLength(maxLength: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('maxLength', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [maxLength] = msgData.limits as number[];
return value.length <= maxLength;
},
limits: limitsGetter1(maxLength),
message: messageGetter(MEMBER_MESSAGES.maxLength, message)
});
this._pushRule();
return this;
}
/**
* 弹性长度
* @param {ValidationLimit<number>} minLength
* @param {ValidationLimit<number>} maxLength
* @param {ValidationMessage} message
* @returns {Validation}
*/
public flex(
minLength: ValidationLimit<number>,
maxLength: ValidationLimit<number>,
message?: ValidationMessage
): Validation {
this._createRule('flex', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const { length } = value;
const [minLength, maxLength] = msgData.limits as number[];
return length >= minLength && length <= maxLength;
},
limits: limitsGetter2(minLength, maxLength),
message: messageGetter(MEMBER_MESSAGES.flex, message)
});
this._pushRule();
return this;
}
/**
* 指定长度
* @param {ValidationLimit<number>} length
* @param {ValidationMessage} message
* @returns {Validation}
*/
public length(length: ValidationLimit<number>, message?: ValidationMessage): Validation {
this._createRule('length', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [length] = msgData.limits;
return value.length === length;
},
limits: limitsGetter1(length),
message: messageGetter(MEMBER_MESSAGES.length, message)
});
this._pushRule();
return this;
}
/**
* 枚举匹配
* @param {ValidationLimit<AnyArray>} enums
* @param {ValidationMessage} message
* @returns {Validation}
*/
public enum(enums: ValidationLimit<AnyArray>, message?: ValidationMessage): Validation {
this._createRule('length', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [enums] = msgData.limits;
return (enums as AnyArray).some((match) => match === value);
},
limits: limitsGetter1(enums),
message: messageGetter(MEMBER_MESSAGES.enum, message)
});
this._pushRule();
return this;
}
/**
* 正则匹配
* @param {ValidationLimit<RegExp | string>} pattern
* @param {ValidationMessage} message
* @returns {Validation}
*/
public pattern(pattern: ValidationLimit<RegExp | string>, message?: ValidationMessage): Validation {
this._createRule('pattern', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [pattern] = msgData.limits;
if (isRegExp(pattern)) return pattern.test(value);
return value.indexOf(pattern) > -1;
},
limits: limitsGetter1(pattern),
message: messageGetter(MEMBER_MESSAGES.pattern, message)
});
this._pushRule();
return this;
}
/**
* 与……相同
* @param {ValidationLimit<string>} field
* @param {ValidationMessage} message
* @returns {Validation}
*/
public same(field: ValidationLimit<string>, message?: ValidationMessage): Validation {
this._createRule('same', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [field] = msgData.limits as string[];
return value === source[field];
},
limits: limitsGetter1(field),
message: messageGetter((value, source, rule, schema, msgData) => {
const field = msgData.limits[0];
const desc = schema[field as string];
const target = desc ? desc.label || desc.field : field;
return stringAssign('${field}必须与' + target + '相同', msgData);
}, message)
});
this._pushRule();
return this;
}
/**
* 与……相等
* @param {ValidationLimit<any>} match
* @param {ValidationMessage} message
* @returns {Validation}
*/
public equal(match: ValidationLimit<any>, message?: ValidationMessage): Validation {
this._createRule('equal', {
validator: (value, source, rule, schema, msgData) => {
if (isEmpty(value)) return true;
const [match] = msgData.limits;
return value === match;
},
limits: limitsGetter1(match),
message: messageGetter(MEMBER_MESSAGES.equal, message)
});
this._pushRule();
return this;
}
/**
* 自定义验证规则函数
* @param {ValidationMatcher} matcher
* @param {ValidationMessage} message
* @returns {Validation}
*/
public match(matcher: ValidationMatcher, message?: ValidationMessage): Validation {
const validator = matcherToValidator(matcher);
this._createRule('match', {
validator,
message: messageGetter('${field}不符合规则', message)
});
this._pushRule();
return this;
}
/**
* 添加某些已经定义好的验证规则
* @param {Validation} rules
* @returns {Validation}
*/
public add(rules: Validation): Validation {
rules.rules.forEach((rule) => {
this._currentRule = rule; // objectAssign({}, rule) as ValidationRule;
this._pushRule();
});
return this;
}
/**
* 验证规则是否可用
* @param {ValidationEnable} enable
* @returns {Validation}
*/
public enable(enable: ValidationEnable): Validation {
const { _currentRule } = this;
if (!_currentRule) throw new Error('必须先指定验证规则');
_currentRule.enable = isFunction(enable) ? enable : () => enable;
return this;
}
/**
* 指定触发条件
* @param {string} triggers
* @returns {Validation}
*/
public trigger(...triggers: string[]): Validation {
const { _currentRule } = this;
if (!_currentRule) throw new Error('必须先指定验证规则');
_currentRule.triggers = triggers;
return this;
}
/**
* 验证字段是否生效
* @param {ValidationUsable} usable
* @returns {Validation}
*/
public usable(usable: ValidationUsable): Validation {
const { _currentDesc } = this;
if (!_currentDesc) throw new Error('必须先指定验证字段');
_currentDesc.usable = isFunction(usable) ? usable : () => usable;
return this;
}
/**
* 表单验证
* @param {AnyObject} source 原始数据
* @param {Partial<ValidationOptions> | ValidationCallback} [options] 配置
* @param {ValidationCallback} [callback] 回调
* @returns {Promise<boolean> | void}
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
public validate(
source: AnyObject,
options?: Partial<ValidationOptions> | ValidationCallback,
callback?: ValidationCallback
): Promise<boolean> | void {
const faultify = (faults: Fault[]): Fault => new Fault({ message: faults[0].message, faults });
const callbackMode = (options: Partial<ValidationOptions>, callback: ValidationCallback): void => {
this._validate(source, options).then((faults) => {
if (faults.length === 0) {
callback(null, true);
return;
}
callback(faultify(faults), false);
});
};
const promiseMode = (options: Partial<ValidationOptions>): Promise<boolean> => {
return new Promise((resolve, reject) => {
this._validate(source, options).then((faults) => {
if (faults.length === 0) return resolve(true);
reject(faultify(faults));
});
});
};
// validate(source, options, callback);
if (isObject(options) && isFunction(callback)) {
return callbackMode(options, callback);
}
// validate(source, options);
if (isObject(options)) {
return promiseMode(options);
}
// validate(source, callback);
if (isFunction(options)) {
return callbackMode({}, options);
}
return promiseMode({});
}
public destroy(): void {
(this._fieldList as any) = null;
(this._schema as any) = null;
(this._currentDesc as any) = null;
(this._currentField as any) = null;
(this._currentLabel as any) = null;
}
private _createRule(type: ValidationMemberName, assigned: Partial<ValidationRule>): ValidationRule {
if (!this._currentField) throw new Error('必须先指定验证字段');
const rule = objectAssign<ValidationRule>(
{
[VALIDATION_FLAG]: VALIDATION_FLAG,
type,
triggers: [],
limits: () => [],
enable: () => true
},
assigned
);
this._currentRule = rule;
return rule;
}
private _pushRule(): void {
(this._currentRuleList as ValidationRules).push(this._currentRule as ValidationRule);
}
private async _validate(source: AnyObject, options: Partial<ValidationOptions>): Promise<Fault[]> {