I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it.
<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>
However, I am facing an issue where errors are displayed immediately when the page loads, which can be disruptive for users. I want the errors to appear only after the user has interacted with the input/select element.
I attempted to use @blur="$v.form.dobYear.$touch()" but it doesn't seem to be working properly. What could be causing this problem?
Here is a snippet of how my validation rules are defined in the script:
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;
})
}
}
}