Search code examples
vue.jserror-handlingsubmitvee-validate

Vee Validate 3 catch errors on form submit


How do i catch if form submit fails in vee-validate? I have the following component

<template>
  <ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' v-slot='{ handleSubmit }'>

   <form
      @submit.prevent='handleSubmit(onSubmit)'
      class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
      :class="{'is-loading' : isLoading}"
    >
      <div class='flex flex-wrap -mx-3 mb-6'>
        <div class='w-full md:w-3/12 px-3 mb-6 md:mb-5'>
          <ValidationProvider v-slot='{ classes, errors }' rules='required' name='Anrede'>
          <CustomSelect :options='gender'
                        placeholder='Anrede *'
                        v-model='form.gender'
                        :class="classes"
          />
            <span class='text-mb-error font-medium text-sm italic'>{{ errors[0] }}</span>
          </ValidationProvider>
        </div>
</div>
   <div class='block'>
        <button
          class='bg-secondary hover:bg-secondary-200 text-white py-3 px-4 w-full mt-5 focus:outline-none'
          type='submit'
        >
          Registrieren
        </button>
      </div>
    </form>
  </ValidationObserver>
</template>

as method I have the following function

 onSubmit () {
      alert()
      console.log(this.$refs.observer)

      this.$emit('onSendRegistration', this.form)
    }

which works fine if form is valid but if it fails never gets executed. Where can I catch if form validation fails?


Solution

  • As per the documentation:

    [handleSubmit] calls validation like validate and mutates provider's state, accepts a callback to be run only if the validation is successful.

    So to run a callback in the case of an error in validation you would have to trigger the validation programmatically using a ref in the ValidationObserver.

    Your opening ValidationObserver tag would now look like this:

    ...
    <ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' ref='form'>
    ...
    

    Your opening form tag should be now like this:

    ...
    <form
      @submit.prevent='onSubmit'
      class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
      :class="{'is-loading' : isLoading}"
    >
    ...
    

    And your onSubmit method should be something like this:

    onSubmit () {
      this.$refs.form.validate().then(success => {
        if (!success) {
          // run your error code here
        }
    
        alert('Form has been submitted!');
    
      });
    }
    

    Besides this programmatic approach there's no equivalent to handleSubmit for running a callback function after an invalid form submission.

    Check the docs for more info about the programmatic access with $refs.