vee-validate

repository·main·Indexed 11 days ago

https://github.com/logaretm/vee-validate

A UI-agnostic form validation library for Vue.js providing declarative validation, flexible sync/async rules, and a Composition API. It includes specialized helpers for tracking form state (dirty, touched, valid), a Nuxt module for auto-imports and schema detection, and a collection of Laravel-like validation rules via @vee-validate/rules.

Tokens
62.4K
Snippets
207
Records
255
Agent score
89%

What's inside vee-validate

  1. Overview of Composition API Helpers

    main

    Vee-validate provides a collection of Composition API helpers that allow you to opt-in to specific parts of form state and actions without needing to use the full useForm or useField hooks. These helpers are useful for building specialized UI components such as:

    • Custom submission progress indicators
    • Custom error message components
    • Form validity indicators
    • Custom reset or submit buttons
  2. Define a form schema for dynamic rendering

    main

    A form schema is a JavaScript object used to drive the generation of form fields. Each field in the fields array should contain the following properties:

    • label: A friendly string to display as the field label.
    • name: A unique identifier for the field (used for validation and data binding).
    • as: The HTML element type to render (e.g., 'input', 'select').
    • type: (Optional) The HTML input type (e.g., 'password', 'email').
    • rules: (Optional) Validation rules (e.g., using yup).
    • children: (Optional) An array of objects for slotted inputs like <option> elements in a <select>.
    const formSchema = {
      fields: [
        {
          label: 'Your Name',
          name: 'name',
          as: 'input',
          rules: Yup.string().required(),
        },
        {
          label: 'Favorite Drink',
          name: 'drink',
          as: 'select',
          children: [
            { tag: 'option', value: 'coffee', text: 'Coffee' },
            { tag: 'option', value: 'tea', text: 'Tea' },
          ],
        },
      ],
    };
  3. Requirements for Checkbox and Radio Inputs

    main

    To use HTML checkboxes or radio inputs (or custom components acting as such) with vee-validate, ensure the following requirements are met:

    1. Form Context: The fields must be inside a Form component or a custom component created using the useForm API.
    2. Naming: All inputs in a group (e.g., a set of radio buttons or a set of checkboxes) must have the same name prop.
    3. Type Attribute: The fields should have a type attribute (type="checkbox" or type="radio").
  4. How @vee-validate/nuxt works

    main

    The @vee-validate/nuxt module provides several developer experience improvements for Nuxt projects:

    1. Auto-imports: Automatically imports vee-validate components and composables so they are available in your templates and script setup without manual import statements.
    2. Schema Detection: Automatically detects if you are using zod or yup and exposes the appropriate toTypedSchema helper.
    3. Type Safety: While the module avoids exposing types by default to prevent conflicts with other libraries, you can still import all necessary types directly from the main vee-validate package.
  5. Localize field names in messages

    main

    You can map technical field names to human-readable names in different languages by adding a names property to your locale dictionary. When a rule fails, @vee-validate/i18n will attempt to replace the field name with the corresponding entry in the names object for the active locale.

    import { configure } from 'vee-validate';
    import { localize } from '@vee-validate/i18n';
    
    configure({
      generateMessage: localize({
        en: {
          names: {
            age: 'Age',
          },
        },
        ar: {
          names: {
            age: 'السن',
          },
        },
      }),
    });
  6. Track submission progress with `isSubmitting`

    main

    To show loading indicators or disable submit buttons during an API call, use the isSubmitting slot prop.

    isSubmitting becomes true when validation starts (via a submit event) and remains true until your submission handler (passed to onSubmit or handleSubmit) completes or throws an error.

    Note: Calling the validate() function manually does not change the isSubmitting state; it only changes when an actual submission attempt is triggered.

    <template>
      <Form v-slot="{ isSubmitting }">
        <Field name="email" />
        <button :disabled="isSubmitting">
          {{ isSubmitting ? 'Submitting...' : 'Submit' }}
        </button>
      </Form>
    </template>
  7. Important caveats for using ErrorMessage

    main

    When using the ErrorMessage component, keep the following constraints in mind:

    • Form Context: The ErrorMessage component must be used inside a Form component; otherwise, it cannot access the error state.
    • Scope: ErrorMessage can only display errors for fields that exist within the same Form. It cannot reference fields located in a different form.
  8. How Radio and Checkbox values are collected

    main

    Vee-validate manages the collection of values for these input types as follows:

    • Radio Inputs: Radio groups must have type="radio" and the same name. The currently selected value is assigned to the values object under the field's name key.
    • Checkbox Inputs (Multiple): When multiple checkboxes share the same name and have type="checkbox", their selected values are collected into an array, mimicking standard v-model behavior.
    • Checkbox Inputs (Single): If only one checkbox is associated with a name, its value is assigned directly to the values object as a single value rather than an array.
  9. Handle form submissions (AJAX vs Native)

    main

    The <Form /> component handles different submission styles automatically:

    1. AJAX/JavaScript Submissions: If you add a @submit listener to the <Form /> component, vee-validate assumes you are using JavaScript. It automatically calls event.preventDefault() and only executes your handler if the form is valid, passing the form values as the first argument.

    2. Native HTML Submissions: If you do not have a @submit listener, vee-validate assumes a native submission (which causes a page reload). It will still intercept the submission to ensure the form is valid before allowing the browser to proceed with the method and action specified.

    <!-- Native HTML submission example -->
    <Form method="post" action="/api/users" :validation-schema="schema">
      <Field name="email" type="email" />
      <Field name="name" />
      <Field name="password" type="password" />
    
      <button>Submit</button>
    </Form>
  10. Integrate vee-validate with Vue UI libraries

    main

    vee-validate is UI-agnostic and does not provide special treatment for specific components. It works with any UI library as long as the components emit the correct events and allow for outsourcing form logic to a third party.

    Integration strategies vary depending on how a library tracks field values and manages its internal form state. If a UI library's built-in validation is insufficient, you can use vee-validate to power the validation logic for those components.

  11. Understand event-based validation triggers

    main

    Vee-validate provides granular control over which DOM or Vue events trigger validation.

    Scope Limitation: The following event-based configuration options apply only to the <Field /> component and do not affect the useField composable:

    • validateOnBlur
    • validateOnChange
    • validateOnInput
    • validateOnModelUpdate

    To control these, use the configure function with the desired boolean values.