直接上代码:
封装验证器:
export function isvalidPhone(phone) {
const isPhone = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/ //11位合法手机号码
const isMob1 = /0\d{2,3}\d{7,8}/ //不带-的座机:02985111752
const isMob2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/ //带一个-:029-85111752
const isMob3 = /^\d{3,4}-\d{3,4}-\d{3,4}$/; //带三个-: 0752-250-520
if (isMob1.test(phone) || isMob2.test(phone) || isMob3.test(phone) || isPhone.test(phone)) {
return true
} else {
return false
}
}
export function validEmail(email) {
const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
return reg.test(email)
}
组件中使用:
form表单中写入自定义校验规则
data() {
const validPhone = (rule, value, callback) => {
if (!value) {
callback()
} else if (!isvalidPhone(value)) {
callback(new Error('请输入合法的电话号码'))
} else {
callback()
}
}
const validMail = (rule, value, callback) => {
if (value === '' || value === null) {
callback()
} else if (value === this.email) {
// callback(new Error('新邮箱不能与旧邮箱相同'))
} else if (validEmail(value)) {
callback()
} else if (!validEmail(value)) {
callback(new Error('请输入合法的邮箱'))
}
return{
rules: {
custName: [
{ required: true, message: '请输入客户名称', trigger: 'blur' }
],
phone: [
// { required: false, message: '请输入联系电话', trigger: 'blur' },
{ required: false, validator: validPhone, trigger: 'blur' }
],
email: [
{ required: false, validator: validMail, trigger: 'blur' }
]
}
}
}
看效果:
失焦后进行校验。