写了一段时间的vue,前端用了element-ui,经常会用到from表单,总结一下form表单的校验,以及遇到过的问题。
1、正常添加校验流程,在form表单加rule
2、只想对单个input校验
3、自定义校验(例如用正则校验手机号码、数字、url、中文等)
4、添加动态校验(可以根据需要显示校验或者改变校验规则)
5、遇到校验无效的问题
一:正常添加校验流程,在form表单加rule
1、在el-form里面添加:rules=“rules”
2、在el-form-item里面添加prop,prop对应:model="form"的form的属性
3、然后在data里面添加属性rules
4、在点击提交的按钮里面validate的校验
.....
data() {
return {
//在rules属性填写相关字段的校验规则
rules: {
username: [
{ required: true, message: "必填" },
{ min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
],
email:[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' }],
}
}
}
methods: {
onSubmit() {
this.$refs.form.validate((valid) => {
if (valid) {
//调用接口保存
} else {
this.$message.error('请完善表单相关信息!');
return false;
}
});
},
//或者
onSubmit() {
if(!this.checkForm()){
this.$message.error('请完善表单相关信息!');
return;
}
//调用接口保存
},
// 表单校验
checkForm(){
// 1.校验必填项
let validForm = false;
this.$refs.form.validate(valid => {validForm = valid})
if(!validForm){
return false;
}
//其他的校验
/*if(){
return false;
}*/
return true;
}
}
二:对单个input校验
有时候并不想在form增加rules校验,只想对单个input增加校验,直接在el-form-item里面加rules
三:自定义校验(正则校验手机号码、数字、url、中文)
提供几个用正则表达式做的自定义校验规则demo
data() {
return {
//在rules属性填写相关字段的校验规则
rules: {
username: [
{ required: true, message: "必填" },
{ min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
],
email:[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' }],
//自定义校验
name:[
{ required: true, message: '请输入姓名', trigger: 'blur' },
{ validator:function(rule,value,callback){
//校验中文的正则:/^[\u4e00-\u9fa5]{0,}$/
if(/^[\u4e00-\u9fa5]{0,}$/.test(value) == false){
callback(new Error("请输入中文"));
}else{
//校验通过
callback();
}
}, trigger: 'blur'
},
],
phone:[
{ required: true, message: '请输入手机号码', trigger: 'blur' },
{ validator:function(rule,value,callback){
if(/^1[34578]\d{9}$/.test(value) == false){
callback(new Error("请输入正确的手机号"));
}else{
callback();
}
}, trigger: 'blur'
},
],
age:[
{ validator:function(rule,value,callback){
if(/^[0-9]*$/.test(value) == false){
callback(new Error("请输入正确的数字"));
}else{
callback();
}
}, trigger: 'blur'
},
],
url:[
{ validator:function(rule,value,callback){
if(/^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/.test(value) == false){
callback(new Error("请输入正确的Url"));
}else{
callback();
}
}, trigger: 'blur'
},
],
}
}
}
四:添加动态校验(可以根据需要显示校验或者改变校验规则)
遇到过一种,根据form表单的一个下拉列表的选项来判断某些字段是否校验,选了A,要校验几个字段必填,选了B又要校验其他几个字段必填,这时候表单的校验需要动态添加,这时候我们需要动态改变rules属性相关的校验即可
例如刚刚这种根据下拉列表的选项来动态触发校验的,那么在el-select里面加@change事件,每次下拉列表改变就触发事件来改变form表单的校验规则
data() {
return {
//在rules属性填写相关字段的校验规则
rules: {
phone: [{ required: true, message: "必填" }],
email:[{ required: true, message: "必填" }],
}
}
},
methods: {
//改变状态时动态重置校验规则
resetValidate(){
if(this.form.status== 1){
//重置rules的phone、email的属性值,只校验手机,不校验邮箱
this.rules.phone= [{ required: true, message: "必填" }];
this.rules.email= [];
}else{
//只校验邮箱,不校验手机
this.rules.phone= [];
this.rules.email= [{ required: true, message: "必填" }];
}
this.$refs.form.clearValidate();
},
}
五:validator用法
validator验证器,可以对格式进行复杂限制,
跟rule一样需要设置对应表单项的prop属性,然后绑定validator,validator绑定验证规则变量(注意验证规则变量是处在data的return外面)。
data() {
//rule表示要验证的规则,value表示输入值,callback回调
var checkEmail = (rule, value, callback) => {
let mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
if (!value) { //如果输入为空直接返回
callback();
} else {
//如果字符串 string 中含有与 RegExpObject 匹配的文本,则返回 true,否则返回 false。
if (mailReg.test(value)) { //匹配成功返回
callback();
} else { //匹配不成功返回错误显示
callback(new Error("邮箱格式:[email protected],只含数字、大小写字母、下划线、横杠"));
}
}
};
var checkPhone = (rule,value,callback) =>{
let phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
if(!value){
callback()
}else{
if(phoneReg.test(value)){
callback()
}else{
callback(new Error("电话格式:13、14、15、17、18开头+9位阿拉伯数字"))
}
}
}
return {
isEdit: false,
user: {},
tempUser: {},
rules: {
userName: [
{ required: true, message: "请输入昵称", trigger: "blur" },
// { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
account: [
// { required: true, message: "请输入账户", trigger: "blur" },
// { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
userEmail: [
{ validator: checkEmail, trigger: "blur" },
],
phone: [
{ validator: checkPhone,trigger: "blur" },
],
},
};
},
在方法中判断验证器是否全部通过:
// valid在全部validator通过才会返回true,否则为false
this.$refs.userForm.validate((valid) => {
if (!valid) {
this.message("warning", "请修改正确的数据格式!");
return;
} else {
//验证通过调用保存接口
}
六:遇到校验无效的问题
有一次遇到一个校验无效的问题,from表单其他字段校验都有效,就是有一个el-date-picker的校验一直没有效果,检查发现在el-form-item里面添加prop,prop对应:model="form"的form的属性并不是当前form里面的属性值.,所以这个el-date-picker没有触发校验
.....
// 1.里面的el-input绑定的username必须是:model="form"的form里面的属性
// 2.并且el-form-item的prop=username,才会校验生效,否则在element-ui会没有校验效果
七:案例
ruleInline : {
claimTypeId: [{ required: true, message: '赔付类型必选', trigger: 'change' }],
trackNo: [{ required: true, message: '订单号必填', trigger: 'blur' }],
areaId: [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
receiveMobile: [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
claimMoney: [{ validator: Format.FormValidate.Form().moneyAmount, required: true, trigger: 'blur' }],
claimName: [],
receiverName: [],
claimEvidence: [],
remark: []
// claimName: [{ required: true, message: '责任人必填', trigger: 'blur' }],
// receiverName: [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
// claimEvidence: [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
// remark: [{ required: true, message: '问题描述必填', trigger: 'blur' }]
}
// 赔付类型
changeSelect(e) {
this.claimStatusName = this.$refs.refStatus.$slots.default[e].child.label
if (e === '2') {
this.ruleInline.claimTypeId = [{ required: true, message: '赔付类型必选', trigger: 'change' }],
this.ruleInline.trackNo = [{ required: true, message: '订单号必填', trigger: 'blur' }],
this.ruleInline.areaId = [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
this.ruleInline.receiveMobile = [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
this.ruleInline.claimMoney = [{ validator: Format.FormValidate.Form().money, required: true, trigger: 'blur' }],
this.ruleInline.claimName = [{ required: true, message: '责任人必填', trigger: 'blur' }],
this.ruleInline.receiverName = [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
this.ruleInline.claimEvidence = [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
this.ruleInline.remark =[{ required: true, message: '问题描述必填', trigger: 'blur' }]
// this.ruleInline = {
// claimTypeId: [{ required: true, message: '赔付类型必选', trigger: 'change' }],
// trackNo: [{ required: true, message: '订单号必填', trigger: 'blur' }],
// areaId: [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
// receiveMobile: [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
// claimMoney: [{ validator: Format.FormValidate.Form().money, required: true, trigger: 'blur' }],
//
// claimName: [{ required: true, message: '责任人必填', trigger: 'blur' }],
// receiverName: [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
// claimEvidence: [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
// remark: [{ required: true, message: '问题描述必填', trigger: 'blur' }]
// }
} else {
this.ruleInline.claimName = []
this.ruleInline.claimMoney = []
this.ruleInline.receiverName = []
this.ruleInline.claimEvidence = []
this.ruleInline.remark = []
}
this.$refs.formInline.clearValidate()
},
案例二:
data() {
const vm = this
var checkMoney = (rule, value, callback) => {
debugger
if (value >= vm.formInline.deductionAmount) {
callback(new Error('应追回金额小于等于赔付金额'))
} else {
// 校验通过
callback()
}
}
return {
// 退款状态
refundedStatusType: [
{
code: 'YZH',
name: '已追回'
}, {
code: 'DZH',
name: '待追回'
}
],
// 对其方式
labelPosition: 'right',
// 定义一个IsShow来接收传递过来的值
IsShow: this.modal,
formInline: {
fkClaimId: null,
// 主键Id
pkCancelClaimId: null,
// 运单号
trackNo: null,
// 快递商
supplierCode: null,
// 责任人
personLiable: null,
// 已赔付金额
claimAmount: null,
deductionAmount: null,
// 待退款金额
beforeRefundedAmount: null,
// 退款金额
refundedAmount: null,
// 撤销原因
cancelReason: null,
// 退款状态
refundedStatus: null
},
ruleInline: {
refundedStatus: [{ required: true, message: '追回状态必选', trigger: 'change' }],
cancelReason: [{ required: true, message: '撤销原因必填', trigger: 'blur' }],
// deductionAmount 赔付金额 追回金额,必须必赔付金额小或等于
beforeRefundedAmount: [
{ required: true, message: '应追回金额必填', trigger: 'blur' },
{ validator: checkMoney, trigger: 'blur' }
/* { validator: function(rule, value, callback) {
debugger
console.log(rule, value)
// 校验中文的正则:/^[\u4e00-\u9fa5]{0,}$/
console.log(this.formInline.beforeRefundedAmount)
console.log(this.formInline.deductionAmount)
if (value <= this.formInline.deductionAmount) {
callback(new Error('应追回金额应该小于等于赔付金额'))
} else {
// 校验通过
callback()
}
}, trigger: 'blur'
}*/
],
refundedAmount: [{ required: true, message: '应退款金额必填', trigger: 'blur' }]
}
}
},
const vm = this
var checkMoney = (rule, value, callback) => {
debugger
if (value <= vm.formInline.deductionAmount) {
// 校验通过
callback()
} else {
callback(new Error('应追回金额小于等于赔付金额'))
}
}
var refundedMoney = (rule, value, callback) => {
debugger
if (value <= vm.formInline.beforeRefundedAmount) {
// 校验通过
callback()
} else {
callback(new Error('追回金额小于等于应追回金额'))
}
}
ruleInline: {
refundedStatus: [{ required: true, message: '追回状态必选', trigger: 'change' }],
cancelReason: [{ required: true, message: '撤销原因必填', trigger: 'blur' }],
// deductionAmount 赔付金额 追回金额,必须必赔付金额小或等于
beforeRefundedAmount: [
{ required: true, message: '应追回金额必填', trigger: 'blur' },
{ validator: checkMoney, trigger: 'blur' }
],
refundedAmount: [{ required: true, message: '应退款金额必填', trigger: 'blur' },
{ validator: refundedMoney, trigger: 'blur' }]
}