Sanakey
2021-07-09 3fc241d02fb8b671289de3d9d80bf848349c04d4
提交 | 用户 | age
ff3df3 1 // interface weValidator {
S 2 //   checkFields(data: object, fields:Array<string>, onMessage?: Function, showMessage?: boolean):boolean;
3 //   checkData(data: object, onMessage?: Function, showMessage?: boolean, fieldMap?: object): boolean;
4 // }
5 type Options = {
6   rules: object,
7   messages: object,
8   onMessage?: Function,
9   multiCheck?: boolean
10 }
11 const WeValidator = require('we-validator');
12
13 class MyValidator {
14   public validator: any
15   constructor(public options:Options,public pageInstance:any) {
16     this.options = options;
17     this.validator = new WeValidator(options);
18     this.pageInstance = pageInstance;
19   }
b6cc28 20   addRules(rules:object){
S 21     // 动态添加校验
22     this.validator.addRules(rules);
23   }
24   removeRules(fields:Array<string>){
25     // 动态删除校验
26     this.validator.removeRules(fields);
27   }
ff3df3 28   checkField(type: string,value: string){
S 29     value = value.trim();
b6cc28 30     let msg = '';
ff3df3 31     this.pageInstance.setData({[type]:value});
S 32     if(!this.validator.checkFields({[type]:value},[`${type}`],(data:any)=>{
33       console.log(data);
34       this.pageInstance.setData({
35         [`${type}Error`]:data[type].msg
36       })
b6cc28 37       msg = data[type].msg;
S 38     })) return msg;
ff3df3 39     this.pageInstance.setData({
S 40       [`${type}Error`]:''
41     })
b6cc28 42     msg = '';
S 43     return msg;
ff3df3 44     // console.log((this as any).validatorInstance.checkFields({username:value},['username']));
S 45     // console.log((this as any).validatorInstance.isValid({username:value},['username']));
46
47     // if(!(this as any).validatorInstance.checkData(value)) return
48   }
49   checkAllData():boolean {
50     interface errorType {
51       [property:string]:any;
52     }
53     let value:any = {};
3fc241 54     let rules = this.getRulers();
S 55     rules.forEach((key) => {
ff3df3 56       value[key] = this.pageInstance.data[key]
S 57     })
58     return this.validator.checkData(value,(data:any)=>{
59       let error: errorType = {};
60       for (let type in data) {
61         if (data.hasOwnProperty(type)) {
62           error[`${type}Error`] = data[type].msg
63         }
64       }
65       this.pageInstance.setData(error)
b6cc28 66       console.log(data,error);
ff3df3 67     })
S 68   }
3fc241 69   getRulers(){
S 70     let keys = Object.keys(this.options.rules);
71     console.log('keys',keys);
72     return keys;
73   }
7a3e75 74
S 75   static addRule(rulesName:string,rules:object) {
76     WeValidator.addRule(rulesName,rules);
77   }
ff3df3 78 }
S 79
80 export default MyValidator