21行代码撸一个JavaScript表单验证器(仿lumen Validator)

478 阅读1分钟

本人菜鸟一枚,第一次在掘金发文章

验证下面的数据

//等待验证的数据
let awitWerified = {
    //必须填写、必须是string类型、最小长度6位、最大长度10位
    name:'123',
    //必须填写、必须是手机号
    phone:'15211111198'
}

编写规则

let rules={
    // 必填
    required: function(value, errorMsg='不能为空') {
        if(value === ''|| value == null) {
            return errorMsg
        }
    },
    // 最小值
    min: function(value, length, errorMsg=`${value.length?'长度':''}不能小于${length}`){
        let val = value.length || value
        if(val < length) {
            return errorMsg
        }
    },
    // 最大值
    max: function(value, length, errorMsg=`${value.length?'长度':''}不能大于${length}`){
        let val = value.length || value
        if(val > length) {

            return errorMsg
        }
    },
    // 手机号校验
    mobile:function(value, errorMsg=`手机号码不正确`){
        if(!/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[0-9])\d{8}$/.test(value)){
            return errorMsg
        }
    },
    // 字符串类型
    string:function(value, errorMsg='必须为字符串类型') {
        if(typeof value !== "string"){
            return errorMsg
        }
    },
}

实现核心类(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)
    }
}

简单调用

//等待验证的数据
let awitWerified = {
    name:1,
    phone:'15210328198'
}
//通过Validator的make方法
let validatorError = new Validator().make(awitWerified, {
    'name' : 'required|string|min:6|max:10',
    'phone' : 'required|phone',
});

if (validatorError) {
   console.log(validatorError)
}
输出如下