自定义表单校验
<el-form :model="Formdata" ref="formRef" :rules="nodeFormRules" label-width="100px">
<el-form-item
label="年龄"
prop="age"
>
<el-input v-model.number="Formdata.age"></el-input>
</el-form-item>
</el-form>
data() {
var checkNumber = (rule, value, callback) => {
// if (!value) {
// return callback(new Error('年龄不能为空'));
// }
if (value && !Number.isInteger(value)) {
callback(new Error("请输入数字值"));
} else {
callback();
}
};
return{
nodeFormRules: {
age: [{ validator: checkNumber, trigger: "blur" }],
}
}
}
只要给el-form标签加上prop
和rules
属性就可以了
<el-form :model="Formdata" ref="formRef" label-width="100px">
<el-form-item
label="年龄"
prop="age"
:rules="[
{ required: true, message: '年龄不能为空'},
{ type: 'number', message: '年龄必须为数字值'}
]"
>
<el-input v-model.number="Formdata.age"></el-input>
</el-form-item>
</el-form>
注意:
el-form标签的prop属性的值必须得和input框v-model绑定的值一致,否则校验无效
一打开表单 还没开始输入数据 表单的校验就自动触发了
这就导致我的空表单出现了校验错误
在表单页面mounted中 或者 打开表单页面之前 移除表单项的校验结果,即在对应位置加上如下代码:
this.$nextTick(() => {
setTimeout(() => {
this.$refs.formRef.clearValidate(); // 移除表单项的校验结果
}, 10);
});
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="密码" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
var checkAge = (rule, value, callback) => {
if (!value) {
return callback(new Error('年龄不能为空'));
}
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error('请输入数字值'));
} else {
if (value < 18) {
callback(new Error('必须年满18岁'));
} else {
callback();
}
}
}, 1000);
};
var validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error('请输入密码'));
} else {
if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass');
}
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('请再次输入密码'));
} else if (value !== this.ruleForm.pass) {
callback(new Error('两次输入密码不一致!'));
} else {
callback();
}
};
return {
ruleForm: {
pass: '',
checkPass: '',
age: ''
},
rules: {
pass: [
{ validator: validatePass, trigger: 'blur' }
],
checkPass: [
{ validator: validatePass2, trigger: 'blur' }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>