elementUI表单验证
elementUI表单验证非常方便,我们直奔主题:
<template> <el-form ref="orderForm" :model="orderForm" :rules="addRules" label-width="100px"> <el-form-item label="联系人:" prop="contact"> <el-input v-model="orderForm.contact" type="text" placeholder="请输入联系人名称"></el-input> </el-form-item> <el-form-item label="联系电话:" prop="phone"> <el-input v-model="orderForm.phone" type="text" placeholder="请输入联系电话"></el-input> </el-form-item> </el-form> </template> <script> export default { data() { let validateContact = (rules, value, callback) => { if (value === '') { callback(new Error('请输入联系人姓名')); } else { // 中文或英文、数字正则 let regExpr = /^[a-zA-Z0-9 \u4e00-\u9fa5]+$/; if(!regExpr.test(value)){ callback(new Error('联系人输入不正确')); } else if(value && value.trim().length>30) { callback(new Error('长度超出限制')); } else { this.correct = true; // 标记contact是否校验通过 callback(); } } }; let validPhone = (rules, value, callback) => { if (value === '') { callback(new Error('请输入手机号')); } else { if(value){ value = value.trim(); } let TEL_REGEXP = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/; if(TEL_REGEXP.test(value)) { callback(new Error('手机号格式不正确')); } else { this.phoneCorrect = true; // 标记手机号码校验正确 callback(); } } }; return { orderForm: { contact: "", phone: "", }, addRules: { contact: [{ required: true, validator: validateContact, trigger: 'blur'}], phone: [{required: true, validator: validPhone, trigger: 'blur'}], }, correct: false, // 校验是否正确 phoneCorrect: false, // 校验手机号码是否正确 } } } </script>
1、验证表单中的某个字段:
// 验证contact字段 this.$refs.orderForm.validateField("contact", () => { console.log(this.correct); }); // 验证phone字段 this.$refs.orderForm.validateField("phone", () => { console.log(this.phoneCorrect); });
2、验证整个表单:(在提交订单前验证)
this.$refs.orderForm.validate(function (valid){ if(valid){ // TO DO } });
3、表单重置:
this.$refs.orderForm.resetFields();