如何处理提交时的多个验证(Vue.js)



你好,在让用户提交之前,我需要验证几个输入:

<button type="submit" v-on:click="validateErrors()" @click.prevent="submit">Finalizar</button>

我做了一个方法validateErrors,以便分别处理所有的验证:

validateErrors() {
if (this.campaign.selectedBox == null) {
this.$set(this.msg, 'selectedbox', 'Alert 1') ;
return true;
}
if (this.campaign.selectedExtras == null) {
this.$set(this.msg, 'selectedextras', 'Alert 2') ;
return true;
}
},

最后,我用不同的消息发出警报,以便在一个(或多个)输入不验证时显示:

<div class="alert alert-info w-100" v-if="msg.selectedbox">{{msg.selectedbox}}</div>
<div class="alert alert-info w-100" v-if="msg.selectedextras">{{msg.selectedextras}}</div>

只有第一个验证是工作的,我怎么能处理多个验证与他们自己的警报在提交时由同一函数执行?

非常感谢!

您可以为输入添加规则,然后在vjs中使用表单验证器,而不是创建这个函数https://v2.vuejs.org/v2/cookbook/form-validation.html但是如果你想继续使用这个函数你可以这样做

function validateErrors() {
var check1 = false;
var check2 = false;
if (this.campaign.selectedBox == null) {
this.$set(this.msg, "selectedbox", "Alert 1");
check1 = true;
}
if (this.campaign.selectedExtras == null) {
this.$set(this.msg, "selectedextras", "Alert 2");
check2 = true;
}
return {check1:check1, check2:check2};
}

最新更新