我正在使用vee-validate,我有两个字段; 一部用于家庭电话,另一部用于手机.我不需要为规则制定两个"必需",但我需要的是至少其中一个必需.
那么,我的问题是,是否可以设置一个规则来检查两个字段中的至少一个输入?
好的,没多久,但我有这个工作.它只是需要一些挖掘,所以发布我的答案,以便它可以帮助其他人.
首先,我输入栏HOMEPHONE和手机,并将它们中的至少一个是必需的.
可以使用Vue中的计算属性实现以下功能:
computed: {
isHomePhoneRequired() {
if(this.cellphone === '')
return true; // homephone is required
return false;
},
isCellPhoneRequired() {
// check if homephone is empty
if(this.homephone === '')
return true; // cellphone is required
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我的HTML如下所示:
<div class="form-group" :class="{'has-error': errors.has('homephone') }">
<div class="label">Home Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
<div ><input type="text" class="form-control" v-model="homephone" v-validate ="{ rules: { required: this.isHomePhoneRequired} }" data-vv-name="homephone" data-vv-as="Home Phone" /></div>
<p class="text-danger" v-if="errors.has('homephone')">{{ errors.first('homephone') }}</p>
</div>
<div class="form-group" :class="{'has-error': errors.has('cellphone') }">
<div class="label">Cell Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
<div ><input type="text" class="form-control" v-model="cellphone" v-validate ="{ rules: { required: this.isCellPhoneRequired} }" data-vv-name="cellphone" data-vv-as="Cell Phone" /></div>
<p class="text-danger" v-if="errors.has('cellphone')">{{ errors.first('cellphone') }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意,v-validate现在获取一个传递的对象,其中包含类型(规则),要使用的验证(必需)和计算属性(isHomePhoneRequired).