1、首先在el-form标签加上ref和:rules属性,并且在每个el-form-item标签里定义prop属性,prop属性跟:rules里面的每项对应,如:

<el-form :model = " dialogFormData " label-width = "150px" ref = "dialogFormRef" :rules = " dialogFormRules " >    
    <el-form-item label = "uniqueID" prop = "uniqueID" >
        <el-input v-model = " dialogFormData.uniqueID " placeholder = "" ></el-input>
    </el-form-item>
</el-form>

2、在data里面定义rules属性值

dialogFormRules: {
    uniqueID: [{required: true , message: '必填' }, {validator: MyValid.validSixNum}]
}
3、验证表单
this .$refs[ 'dialogFormRef' ].validate((valid) => {
    在这里判断valid的true或false
}
4、自定义验证方法的例子:
//验证长度为6的全数字
validSixNum (rule, value, callback){
    var valArr = value.split( '' );
    console.log( 'vali six num: ' + valArr.length);
    if(valArr.length != 6){
        return callback(new Error('长度必须是6'));
    }
    var re = new RegExp( "^{6}[0-9]*$" );
    if ( ! re.test(value)){
        return callback( new Error( '必须是纯数字' ));
    }
    callback();
}

转载于:https://my.oschina.net/u/222749/blog/2874531

Logo

前往低代码交流专区

更多推荐