<template>
<div id="app">
<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" v-loading="loading" @click="submitForm">提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<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: ''
},
loading: false,
rules: {
pass: [
{ validator: validatePass, trigger: 'blur' }
],
checkPass: [
{ validator: validatePass2, trigger: 'blur' }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
},
methods: {
submitForm() {
const resArr = []
this.$refs.ruleForm.validateField(['pass', 'checkPass'],(valid) => {
resArr.push(valid)
})
// 所有valid等於空字符串時通過校驗
if (resArr.every(v => v === '')) {
// 通過校驗後的操作
this.loading = true
}
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
<style lang="sass">
</style>
elementUI form表单使用validateField方法校验部分表单
最新推荐文章于 2024-08-06 17:26:24 发布
本文展示了使用Vue.js实现表单验证的过程,包括密码、确认密码和年龄验证。通过自定义验证规则,确保用户输入的年龄为数字且大于18,密码与确认密码一致。在提交表单时进行实时验证,只有当所有验证通过后才会触发提交操作。
摘要由CSDN通过智能技术生成