0 套路
- 给要校验的输入框添加校验事件(方法)
- 在方法中定义校验规则reg
- 使用reg.tes(param)方法进行校验,参数:被校验的值;返回值:Boolean,校验通过返回true,失败返回false
- 做提示。对校验结果进行转化提示。
代码示例是基于vue+element-ui的
1 手机号校验
1.1 html
<el-input
v-model="user.phone"
maxlength="11"
@blur="isLegalPhone(user.phone)"
></el-input>
1.2 js
isLegalPhone(phoneNum) {
// console.log(phoneNum);
let reg = /^1[0-9]{10}$/;
if (reg.test(phoneNum)) {
return true;
} else {
this.$notify({
title: '错误',
message: '请输入正确的手机号',
type: 'warning',
duration: 0
});
return false;
}
return reg.test(phoneNum);
},
2 邮箱校验
2.1 HTML代码
<el-input v-model="user.email" @blur="isLegalEmail(user.email)"></el-input>
2.2 js代码
isLegalEmail(email) {
// console.log(email);
let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (reg.test(email)) {
return true;
} else {
this.$notify({
title: '错误',
message: '请输入正确的邮箱',
type: 'warning',
duration: 0
});
return false;
}
},
3 金额校验
3.1 HTML代码
<el-input
placeholder="请输入内容"
v-model="dishData.price"
@blur="isLegalPrice(dishData.price)"
>
</el-input>
3.2 js代码
isLegalPrice(val) {
let reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/;
if (reg.test(val)) {
return true;
} else {
this.$notify({
title: '错误',
message: '请输入正确的金额,最多包含两位小数',
type: 'warning',
duration: 0
});
return false;
}
},