效果图:
完整代码 Demo.vue
<template> <div class="main"> <div> <el-form ref="form" :model="ruleForm" :rules="rules" label-width="80px" class="width-90-percent" > <el-form-item label="姓名" class="margin-bottom-30" prop="name"> <el-input v-model="ruleForm.name" maxlength="20" minlength="3" clearable></el-input> </el-form-item> <el-form-item label="邮箱" class="margin-bottom-30" prop="email"> <el-input v-model="ruleForm.email" clearable maxlength="30" minlength="7"></el-input> </el-form-item> </el-form> </div> <el-button type="primary" @click="submit" :disabled="buttonDisabled" > 提 交 </el-button> </div> </template> <script> import { isvalidEmail } from "../config/validate.js"; export default { data() { return { ruleForm: { name: "", email: "" }, rules: { name: [ { required: true, message: "请输入您的姓名", trigger: "blur" }, { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" } ], email: [{ required: true, trigger: "blur", validator: this.validEmail }] } }; }, methods: { getUserEmail(whereStr) { return new Promise((resolve, reject) => { // ajax check email resolve(0); }); }, async validEmail(rule, value, callback) { if (!value) { callback(new Error("请输入您的邮箱")); } else if (!isvalidEmail(value)) { callback(new Error("请输入正确的邮箱")); } else { let whereStr = { email: value }; let res = await this.getUserEmail(whereStr); if (res > 0) { callback(new Error("该邮箱已被占用")); } else { callback(); } } }, submit() { this.buttonDisabled = true; setTimeout(() => { this.buttonDisabled = false; }, 5000); this.$refs.form.validate(valid => { if (valid) { console.log("验证通过"); let info = {}; info.user_name = this.ruleForm.name; info.email = this.ruleForm.email; // ajax post do something ... } else { console.log("请填写正确的资料信息后再提交!"); } }); } } }; </script>
分析:
template 里面的 el-form
绑定 :model="ruleForm" :rules="rules"
两个属性, :model
绑定表单数据, :rules
绑定验证规则; el-form-item
添加 prop
属性,用来绑定表单域 model 字段。 script data 中使用 rules 进行规则匹配验证
rules: { name: [ { required: true, message: "请输入您的姓名", trigger: "blur" }, { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" } ], email: [{ required: true, trigger: "blur", validator: this.validEmail }] }
{ required: true, message: "请输入您的姓名", trigger: "blur" }
失去交代呢时进行非空判断 { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
判断长度
邮箱,手机号等验证,使用自定义的 validate.js 文件里面的规则判断,这里单独创建一个文件进行验证判断,因为别的页面功能也需要,也可以直接把验证规则判断代码写到对应代码里。
validate.js
// Email function isvalidEmail (str) { const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/ return reg.test(str) } export { isvalidEmail }