Search code examples
javascriptvue.jsfrontendvuelidate

Vuelidate validates on page render


In our Vue application we are using Vuelidate for form validation. There's this behaviour where the fields are validated just as the page renders, when it should only be validated in form submission, as stated in the docs using $v.invalid and $v.touch() on submission handling. Weird thing is that in some pages where it is implemented, it works well. But sometimes, in other pages, it will validate in a way I don't want, but I can't see where I can get around this. Anyone has been through this? Some code snippets.

 <input
      id="name"
      type="text"
      name="name"
      v-model="form.name"
      :class="{
        invalid:
        !$v.form.name.required || !$v.form.name.minLength,
       }"
 />

My data object and validations

data: {
      form: {
      name: '',
      birth: '',
      parentage: '',
    }
 },
 validations: {
   form: {
      name: { required, minLength: minLength(4) },
 }

Method for submission

async submit() {
  this.$v.touch();
  if (!this.$v.$invalid) {
    console.log('Submit');
  }
}

Solution

  • As the page renders vuelidate will run all the form validations. That's how vuelidate works.

    You need to check form for dirty along with it being invalid.

    $v.$dirty() && $v.$invalid()
    

    When you use $v.$touch() or $v.$reset(), vuelidate marks the form as dirty.

    Please read https://vuelidate.js.org/#sub-v-values to understand the importance of these methods.