rules: { phone: [ { required: true, message: '请输入手机号', trigger: 'blur' }, { validator: this.validatePhone, trigger: 'blur' } ] }
validatePhone(rule, value, callback) { const reg = /^1[3-9]\d{9}$/; if (!value) { callback(new Error('请输入手机号')); } else if (!reg.test(value)) { callback(new Error('请输入正确的手机号')); } else { callback(); }
},
rules: { email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: this.validateEmail, trigger: 'blur' } ] }
validateEmail(rule, value, callback) { // Email正则表达式 const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; if (!value) { callback(new Error('请输入邮箱')); } else if (!reg.test(value)) { callback(new Error('请输入正确的邮箱地址')); } else { callback(); } },
完整代码:
<template> <el-form :model="formData" :rules="rules" ref="form" label-width="100px"> <el-form-item label="邮箱" prop="email"> <el-input v-model="formData.email" clearable></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm('form')">提交</el-button> </el-form-item> </el-form> </template> <script> export default { data() { return { formData: { email: '' }, rules: { email: [ { validator: this.validateEmail, trigger: 'blur' } ] } }; }, methods: { validateEmail(rule, value, callback) { if (value && value.trim() !== '') { // Email正则表达式 const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; if (!reg.test(value)) { callback(new Error('请输入正确的邮箱地址')); } else { callback(); } } else { // 不填写邮箱时不进行验证,直接通过 callback(); } }, submitForm(formName) { this.$refs[formName].validate(valid => { if (valid) { // 表单验证通过,可以提交表单 console.log('提交表单'); } else { // 表单验证不通过 console.log('表单验证不通过'); return false; } }); } } }; </script>
标签:手机号,zA,value,else,callback,trigger,格式,邮箱,reg From: https://www.cnblogs.com/tingorb/p/18311131