[JavaScript] data type checking function, interface data pre-post verification

JavaScript type checking functions

directly on the code

Pass in a data object and a validation rule
, check the field type defined in the rule,
return true if passed, false if not passed and throw an exception

let data = {
    
    
    name: new Date()
}

let rule = {
    
    
    name: {
    
    
        type: Number
    }
}

let status = checkData(rule,data)
console.log("验证结果", status)

/*
 * 类型检查器
 * @params
 * rule:object {键名:值类型} JS原生类型
 * data:object {键名:值}
 * 类型枚举
 * String
 * Number
 * Boolean
 * Array
 * Object
 * Date
 * Function
 * Symbol
 */
function checkData(rule,data) {
    
    
    console.log("验证规则",rule)
    console.log("数据",data)
    try{
    
    
        for(let key  in rule){
    
    
            console.log('字段',key)
            console.log('规则类型',rule[key].type)
            if(data[key] === null || data[key] === undefined){
    
    
                throw new Error(key+"值不存在");
            }else{
    
    
                console.log('值类型',data[key].constructor)
                let type = data[key].constructor
                if(type !== rule[key].type){
    
    
                    throw new Error(key+"类型不匹配");
                }
            }
        }
        return true
    }catch (e) {
    
    
        console.log("错误", e)
        return false
    }

}

Guess you like

Origin blog.csdn.net/sky529063865/article/details/119171619