一、首先在el-form標籤加上ref和:rules屬性,而且在每一個el-form-item標籤裏定義prop屬性,prop屬性跟:rules裏面的每項對應,如:ui
<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>
二、在data裏面定義rules屬性值this
dialogFormRules: {
uniqueID: [{required:
true
, message:
'必填'
}, {validator: MyValid.validSixNum}]
}
三、驗證表單
this
.$refs[
'dialogFormRef'
].validate((valid)
=>
{
在這裏判斷valid的true或false
}
四、自定義驗證方法的例子:
//驗證長度爲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();
}