Vue form verification 100 lines

Time:2020-5-23

Vue form verification 100 lines

Code first

Two files, one write logic and one write verification rule;
Features: simple logic, less code, enough;
Do not want to see the code directly create these two files to copy the code, see the bottom use method;
Vue form verification 100 lines
Sample picture
Vue form verification 100 lines

Vue form verification 100 lines

//validator.js
//Import verification rules
var valitatorRules = require('./valitator-rules.js');

export const Validator=function(formName,rules,errors){
// rules:{
//     name:'required|regexp_hanzi',
//     idCont: 'regexp_I'
// }
this.rules = rules;
// let errors = {
//     name:{
//Required: 'cannot be empty',
//         regexp_ Hanzi: 'must be Chinese character'
//     },
//     idCont:{
//         regexp_ 1: 'the ID number is wrong',
//         regexp_ H: 'Hong Kong pass is wrong',
//         regexp_ T: 'Taiwan pass is wrong',
//     }
// };
this.error = errors;
this.form = document.forms[formName];
this.validatorList = [];
this.init();
}
//Initialization
Validator.prototype.init = function(){
for (let key in this.rules){
    let node = this.findNode(key);
    this.validatorList.push({
        name: key,
        value: '',
        childrenNode:node.childrenNode,
        parentNode: node.parentNode,
        borderColor:getComputedStyle(node.childrenNode).borderColor,
        ruleReg:this.defineRule (key),//[{rule:'hanzi',valit atorRules:fn ( this.value ), error: 'please input Chinese character'}]
        errors :'',
    })
}
};
//Dynamic modification of verification rules
Validator.prototype.changeRules = function(rules,param){
let arrs = Object.keys(rules);
this.rules = {
    ...this.rules,
    ...rules
}
this.validatorList.forEach(val => {
    if(arrs.includes(val.name)){
        val.ruleReg = this.defineRule(val.name)
    }
})
if(param){
    return this.validate(param)
}
};
//Verified by
Validator.prototype.validate = function(param){
let errorList =[];
return new Promise((resolve,reject) => {
    for (let key in param){
        this.validatorList.forEach(val => {
            if(val.name == key){
                val.value = param[key];
                this.runValidator(val);
            }
        })
        
    }

    this.validatorList.forEach(val => {
        Object.keys(param).forEach(v => {
            if(val.name == v && val.errors){
                errorList.push(val);
            }
        })
    })
    if(errorList.length > 0){
        reject(this)
    }else{
        resolve()
    }
})
}
//Exposed display errors
Validator.prototype.showError = function(name){
if(name){
    let module;
    this.validatorList.forEach(val => {
        if(val.name == name){
            module = val;
        }
    })
    if(module.errors){
        this.createError(module);
    } 
    
}else{
    this.validatorList.forEach(val => {
        if(val.errors){
            this.createError(val);
        }
        
    }) 
}

}
//Implement calibration tools;
Validator.prototype.runValidator = function(module){

let n = 0;
function run(param){
   if (n>=module.ruleReg.length){
       return
   }
   If ( param.valitatorRules ( module.value )){// verification passed
        module.errors = '';
        n++;
        run(module.ruleReg[n]);
       
    } else{
        module.errors = param.error;
   }
}    
run(module.ruleReg[n]);

if(module.errors.length == 0 && module.newChildNode){
    this.clear(module);
}
}
//Find node
Validator.prototype.findNode= function(childenName){
let form = this.form;
let childrenNode = form.querySelector(`input[name="${childenName}"]`) || form.querySelector(`textarea[name="${childenName}"]`);
let parentNode = childrenNode.parentNode;
return {
    childrenNode,
    parentNode
}
};
//Find validation rules
Validator.prototype.defineRule =function(name){
let rule = [],ruleString='';
for(let key in this.rules){
    if(name == key){
        ruleString = this.rules[key];
    }
}
let arr= ruleString.split('|');

arr.forEach(val => {
    if(valitatorRules[val]){
        console.log(this)
        rule.push({
            rule:val,
            valitatorRules:valitatorRules[val],
            error:this.error[name][val]
        })
    }
})

return rule;
}
//Production error prompt
Validator.prototype.createError = function(module){
if(module.newChildNode){
    module.newChildNode.innerText = module.errors;
    return
}
let newChildNode = document.createElement('div');
newChildNode.className='_errorMessage';
newChildNode.style.color = 'red';
newChildNode.style.fontSize = '12px';
newChildNode.innerText = module.errors;
module.newChildNode = newChildNode;
module.childrenNode.style.borderColor = 'red';
if(module.childrenNode.nextSibling){
    module.parentNode.insertBefore(newChildNode,module.childrenNode.nextSibling);
}else{
    module.parentNode.appendChild(newChildNode);
}
}
//Clear error prompt
Validator.prototype.clear = function(module){
if(module){
    module.childrenNode.style.borderColor = module.borderColor;
    module.parentNode.removeChild(module.newChildNode);
    module.newChildNode = null;
}else{
    this.validatorList.forEach(val => {
        if(val.newChildNode){
            val.childrenNode.style.borderColor = val.borderColor;
            val.parentNode.removeChild(val.newChildNode);
            val.newChildNode = null;
        }
    })
}
}

Here is the verification rule, which is simpler

Note that non empty verification is not handled separately, so more if else is written here;

//validator-rule.js
module.exports= {
hanzi:function(str){
    if(str){
        let reg = /[\u4e00-\u9fa5]/;
        return reg.test(str);
    }else{
        return true;
    }
    
},
required:function(str){
    return !(str.length == 0)
},
I:function(str){
    if(str){
        let reg = /i/;
        return reg.test(str);
    }else{
        return true;
    }
},
H:function(str){
    if(str){
        let reg = /h/;
        return reg.test(str);
    }else{
        return true;
    }
},
T:function(str){
    if(str){
        let reg = /t/;
        return reg.test(str);
    }else{
        return true;
    }
},
}

usage method

**Import {validator} from '@ Src / utils / validator'**
    **Validation rules can be modified and added by yourself @ Src / utils / validator rules**
    ****
    1. Add the form name attribute < form name ='example_ form'></form>
    2. Define error prompt errors ={
        name:{
            Required: 'cannot be empty',
            Hanzi: 'must be Chinese character'
        },
        idCont:{
            1: 'the ID number is wrong',
            H: 'Hong Kong pass is wrong',
            T: 'Taiwan pass is wrong',
        }
    };
    3. Define validation rules={
        name:'required|hanzi',
        idCont: 'I'
    }
    4. Initialize verification instance: this.Validator  =new Validator('example_ form',rules,errors);
    5. Bind verification information: add the name attribute to input and keep it consistent with the error prompt key < input type = "text" name ='name 'V-model ='name' >
    6. Perform verification: pass in the key and value to be verified; 
    this.Validator.validate({
        [name]:this[name],
    }).then(()=>{ 

    }).catch((errorCb)=>{
        console.log(errorCb)
        errorCb.showError (); // display the error prompt. If only one prompt is displayed, pass in the corresponding value errorCb.showError ('name')
    });
    7. Dynamic follow-up verification rules, such as certificate type change:
    this.Validator.changeRules(
        { idCont:this.idType }, // pass in new verification rules
        { idCont:this.idCont }) // pass in the verified key and value for verification
        .then(()=>{

        }).catch((errorCb)=>{
        errorCb.showError('idCont');
    });
    8: Note: each input should be wrapped with div to ensure that the error information position is correctly added;
    this.Validator.clear (); clear all error prompts

Recommended Today

Configure Apache to support PHP in the Apache main configuration file httpd.conf Include custom profile in

In Apache’s main configuration file / conf/ http.conf Add at the bottom Include “D:workspace_phpapache-php.conf” The file path can be any In D: workspace_ Create under PHP file apache- php.conf file Its specific content is [html] view plain copy PHP-Module setup LoadFile “D:/xampp/php/php5ts.dll” LoadModule php5_module “D:/xampp/php/php5apache2_2.dll” <FilesMatch “.php$”> SetHandler application/x-httpd-php </FilesMatch> <FilesMatch “.phps$”> SetHandler application/x-httpd-php-source </FilesMatch> […]