0

I am using vuelidate to validate my form. I want to validate the user input once user moved to the next input field or click out side of the current input field.

  <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$error}">
     <label for="EmailAddress" class="control-label">Email Address</label>
     <input class="form-control" v-model="$v.partner.email.$model" @blur.native="$v.partner.email.$touch()" :class="{'is-invalid':$v.partner.email.$error, 'is-valid':!$v.partner.email.$invalid}"/>
     <div class="invalid-feedback">
         <span v-if="!$v.partner.email.required">please enter a valid email address</span>
         <span v-if="!$v.partner.email.email">please enter a valid email address</span>
     </div>
  </div>

validations: {
  partner: {
    email: { required, email },
  }
},
methods: {
  beforeSave() {
    event.preventDefault();
    if (this.$v.$invalid) {
      alert("Error");
    } else {
      this.save();
    }
  }
}

Currently validation happens only if user type something on another input field. Otherwise it shows the error message even user type a correct email.

enter image description here

If I change the email to an incorrect one, still it shows the email as a valid input letting user to submit the form.

enter image description here

Brutus
  • 163
  • 1
  • 17

1 Answers1

0

First, remove the .native modified from the input and simply use:

<input class="form-control" @blur="$v.partner.email.$touch()"/>

Also, inside beforeSave method call the $touch() event like:

beforeSave() {
  this.$v.$touch();
  if (this.$v.$invalid) {
    alert("Error");
  } else {
    this.save();
  }
}
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Could you please create a [small demo](https://stackoverflow.com/help/minimal-reproducible-example) for this using [codesandbox.io](https://codesandbox.io/s/vue) to show the issue happening. Thanks! – palaѕн Jun 23 '20 at 15:48