我使用 Bootstrap-Vue 构建了以下表单,其中应用了一些 Vuelidation 代码。
<b-form @submit.prevent="onSubmit">
<input type="hidden" name="_token" :value="csrf" />
<transition-group name="fade">
<b-form-select
:class="{ 'hasError': $v.form.dobDate.$error }"
class="mb-3"
name="dobDate"
id="dobDate"
v-model.lazy="$v.form.dobDate.$model"
:options="optionsDays"
v-if="isSixteen"
key="dobDateSelect"
>
<template slot="first">
<option value disabled>Please select a date</option>
</template>
</b-form-select>
</transition-group>
<transition-group name="fade">
<b-form-select
:class="{ 'hasError': $v.form.dobMonth.$error }"
class="mb-3"
name="dobMonth"
id="dobMonth"
v-model.lazy="$v.form.dobMonth.$model"
:options="optionsMonths"
v-if="isSixteen"
value="optionsMonths.key"
key="dobMonthSelect"
>
<template slot="first">
<option value disabled>Please select a Month</option>
</template>
</b-form-select>
</transition-group>
<b-alert
show
variant="danger"
class="error"
v-if="!$v.form.dobYear.required"
>This field is required</b-alert>
<b-alert
show
variant="danger"
class="error"
v-if="!$v.form.dobYear.minLength"
>Field must have at least {{ $v.form.dobYear.$params.minLength.min }} characters.</b-alert>
<b-alert class="error" v-if="!$v.form.dobYear.numeric">Please enter a valid year of birth</b-alert>
<b-alert show variant="danger" v-if="belowSixteen">You are underage</b-alert>
<b-form-input
:class="{ 'hasError': $v.form.dobYear.$error }"
placeholder="Year of Birth"
v-model="form.dobYear"
@blur="$v.form.dobYear.$touch()"
autofocus
class="form-control mb-3"
name="year"
id="year"
maxlength="4"
@keyup="checkAge"
></b-form-input>
<b-button
class="btn btn-lg btn-primary btn-block"
type="submit"
variant="primary"
:disabled="$v.$invalid||belowSixteen"
>Submit</b-button>
<b-alert
show
variant="danger"
v-if="belowSixteen"
class="error mt-3"
>Sorry you have to be over 16 to play</b-alert>
</b-form>
但是目前,当页面加载时,我会立即得到反馈,这可能会让用户感到不安。相反,我希望在用户完成输入/选择时显示错误。
我曾尝试使用 @blur="$v.form.dobYear.$touch()" 但它似乎根本不起作用。我究竟做错了什么?
这是我的验证在我的脚本中的样子的截图:
validations: {
form: {
dobYear: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
numeric
},
dobMonth: {
required: requiredIf(function() {
return this.isSixteen;
})
},
dobDate: {
required: requiredIf(function() {
return this.isSixteen;
})
}
}
}