【发布时间】:2021-05-11 12:29:42
【问题描述】:
我正在使用 vuelidate,需要进行一些自定义验证,但这涉及到考虑不同的字段。例如:我有一个单选按钮可以在 Month 和 Year 之间进行选择
如果我选择 Month 我将有一个 Year Start (2021, 2020,...) 和 Month Start (1, 2, 3...) 下拉菜单和一个 Year End 和 Month End 下拉菜单.
如果我选择 Year,我将有一个 Year Start (2021, 2020,...) 和 Year End (2021, 2020,...) 下拉菜单。
我的问题是我需要验证month 选项是否year start 大于year end 或者它们可以相等并且month start 必须大于month end。
对于year 选项Year start 应该大于Year End
我有这个:
validations() {
return {
form: {
startMonth: {},
startYear: { required },
endMonth: {},
endYear: { required },
}
};
}
这是我想变成自定义验证器的逻辑
if (this.option === "Year") {
if (this.startYear > this.endYear) {
return true;
} else {
return false;
}
}
else if (this.option === "Month") {
if (this.startYear > this.endYear) {
return true;
} else if (this.startYear == this.endYear && parseInt(this.startMonth) > parseInt(this.endMonth)) {
return true;
} else {
return false;
}
}
任何见解,帮助将不胜感激。
更新 可能的解决方案:
<script>
import { validationMixin } from 'vuelidate';
import { required } from 'vuelidate/lib/validators';
data() {
return {
form: {
month: null,
year: null,
compareMonth: null,
compareYear: null
},
};
},
computed: {
disableApply() {
return this.$v.form.$invalid;
},
},
methods: {
validateYear() {
if (this.$v.form.year.$model > this.$v.form.compareYear.$model) {
return true;
} else {
return false;
}
},
validateMonth() {
if (this.validateYear()) {
return true;
}
if (this.$v.form.year.$model === this.$v.form.compareYear.$model && parseInt(this.$v.form.month.$model) > parseInt(this.$v.form.compareMonth.$model)) {
return true;
} else {
return false;
}
}
},
validations() {
return {
form: {
month: { required, validateMonth: this.validateMonth },
year: { required, validateMonth: this.validateYear },
compareMonth: { required, validateMonth: this.validateMonth },
compareYear: { required, validateMonth: this.validateYear },
}
};
}
};
</script>
【问题讨论】:
标签: javascript vue.js vuelidate