element 表单自定义校验备份
涉及开始时间,结束时间,时间间隔
rules
rules: {
startDate: [
{ required: true, message: '请输选择开始时间', trigger: 'change' },
{ validator: startDateRules, trigger: 'change' },
],
endDate: [
{ required: true, message: '请输选择结束时间', trigger: 'change' },
{ validator: endDateRules, trigger: 'change' },
],
maintainInterval: [
{ required: true, message: '请输选择间隔周期', trigger: 'change' },
{ validator: maintainIntervalRules, trigger: 'change' },
],
maintainGrade: [{ required: true, message: '请选择级别', trigger: 'change' }],
},
对应的规则说明
在data(){}中return上面声明对应的规则
const endDateRules = (rule, value, callback) => {
// this.endTime = Date.parse(value);
let end = Date.parse(value);
let start = this.startTime;
let type = this.intervalType;
let interval = 0;
if (start && end) {
if (!type) {
return callback(new Error('请输选择间隔周期'));
} else if (type == 'day') {
interval = 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
callback();
} else if (type == 'week') {
interval = 7 * 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
} else if (type == 'month') {
interval = 30 * 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
} else if (type == 'quarter') {
interval = 90 * 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
} else if (type == 'half') {
interval = 180 * 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
} else if (type == 'year') {
interval = 365 * 24 * 60 * 60 * 1000;
if (start + interval > end) {
return callback(new Error('结束时间应大于或等于开始时间+间隔周期'));
} else {
callback();
}
}
} else {
callback();
}
};
const startDateRules = (rule, value, callback) => {
this.startTime = Date.parse(value);
return callback();
};
const maintainIntervalRules = (rule, value, callback) => {
this.intervalType = value;
return callback();
};
监听
如果间隔周期改变,执行结束时间的表单校验
watch: {
'formData.maintainInterval': {
handler: function (val, oval) {
if (val) {
this.intervalType = val;
this.$refs.planForm.validateField('endDate');
}
},
deep: true,
// immediate: true
},
},