Search code examples
formsvue.jserror-handlingvuetify.jsfast-fail

Vuetify fast fail is not preventing the form from being sent


Vuetify fast fail checks and displays the error message, but the form is sent anyway.

<script setup>

  import { ref } from "vue"
  
  const firstName = ref('')
  const firstNameRules = [
    value => {
      if (value?.length > 3) return true
      return 'First name must be at least 3 characters.'
    }
  ]
   
  function submit() {
    alert(`${firstName}`)  
  }
 
</script>

<template>
  <v-form fast-fail @submit.prevent="submit">
      <v-text-field
        v-model="firstName"
        label="First name"
        :rules="firstNameRules"
      ></v-text-field>
      </v-form>
</template>

The function submit always runs, even with the error being shown. How to make the error checking prevent the form from being submitted?


Solution

  • The :fast-fail prop stops validation when a check fails (in contrast to the default behavior, which always validates all inputs). It has nothing to do with submitting or submit events.

    Instead, the @submit handler receives a SubmitEventPromise, which is a regular submit event merged with a promise. You can await that promise for the validation result and abort the submit if validation failed:

    async function submit(submitEventPromise) {
      const { valid, errors } = await submitEventPromise
      if (!valid) {
        return // abort submit
      }
      ... // perform submit
    }
    

    Here it is in a playground