el-form 表单校验
<el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="60px" @keyup.enter.native="dataFormSubmitHandle()"> <el-form-item prop="name" label="姓名"> <el-input v-model="dataForm.name" placeholder="姓名" /> </el-form-item> <el-form-item prop="email" label="邮箱"> <el-input v-model="dataForm.email" placeholder="邮箱" /> </el-form-item> <el-form-item label="年龄" prop="age"> <el-input v-model.number="dataForm.age"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button> <el-button @click="resetForm()">重置</el-button> </el-form-item> </el-form> <script> var checkAge = (rule, value, callback) => { if (!value) { return callback(new Error('年龄不能为空')); } if (!Number.isInteger(value)) { callback(new Error('请输入数字值')); } else { if (value < rule.max_age) { callback(new Error('必须年满18岁')); } else { callback(); } } }; export default { data() { return { dataForm: { name: '', email: '', age:'' }, rules: { name: [ { required: true, message: '请输入姓名', trigger: 'blur' }, { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' } ], email: [ { required: true, message: '请输入邮箱地址', trigger: 'blur' }, {type: 'email',message: '请输入正确的邮箱地址',trigger: ['blur', 'change'] } ], age: [ {max_age:18, validator: checkAge, trigger: 'blur' }// checkAge自定义规则函数 ] } }; }, methods: { dataFormSubmitHandle() { this.$refs.dataForm.validate(valid => { if (valid) { alert('submit!'); } else { console.log('error submit!!') } }); }, resetForm() { this.$refs.dataForm.resetFields(); } } } </script>
详细的可查看element文档 https://element.eleme.cn/#/zh-CN/component/form