I rookie one, the first time in nuggets hair article

Verify the following data

// Waiting for validation data
let awitWerified = {
    The value must be a string with a minimum length of 6 characters and a maximum length of 10 characters
    name:'123'.// Must be a mobile phone number
    phone:'15211111198'
}
Copy the code

Write rules

let rules={
    / / required
    required: function(value, errorMsg='Cannot be empty') {
        if(value === ' '|| value == null) {
            return errorMsg
        }
    },
    / / the minimum
    min: function(value, length, errorMsg=`${value.length?'length':' '}Not less than${length}`){
        let val = value.length || value
        if(val < length) {
            return errorMsg
        }
    },
    / / Max
    max: function(value, length, errorMsg=`${value.length?'length':' '}Is not greater than${length}`){
        let val = value.length || value
        if(val > length) {

            return errorMsg
        }
    },
    // Check mobile phone number
    mobile:function(value, errorMsg='Incorrect mobile number'){
        if(!/ ^ (13 14 [579] [0-9] | | 15 [0, 3, 5-9] 16 [6] | | 17 [0135678] [0-9] | | 18 19 [0-9]) \ d {8} $/.test(value)){
            return errorMsg
        }
    },
    // A string of characters
    string:function(value, errorMsg='Must be string type') {
        if(typeofvalue ! = ="string") {return errorMsg
        }
    },
}
Copy the code

Implementing core Classes (line 21)

class Validator {
    rules={}
    constructor() {this.rules=rules
    }
    make(data,cheacks){ 
        return Object.keys(cheacks).map(key= >{
            let val = data[key]
            let rules=cheacks[key].split('|')
            return{
                key:key,
                fail:rules.map(rule= >{
                    let arg = rule.split(":")
                    let fnKey = arg.shift()
                    arg.unshift(val)
                    return this.rules[fnKey].apply(val,arg)
                }).filter(val= >val?true:false)
            }     
        }).filter(val= >val.fail.length>0?true:false)}}Copy the code

A simple call

// Waiting for validation data
let awitWerified = {
    name:1.phone:'15210328198'
}
// Use the make method of Validator
let validatorError = new Validator().make(awitWerified, {
    'name' : 'required|string|min:6|max:10'.'phone' : 'required|phone'});if (validatorError) {
   console.log(validatorError)
}
Copy the code
The output is as follows