Vuelidate Documentation

website·Indexed 29 days ago

https://vuelidate-next.netlify.app/

A lightweight model-based validation library for Vue.js 3 and 2. This documentation covers installation, built-in and custom validators via @vuelidate/validators, validation state values, and migration from v0.x to v2.0.

Tokens
11.5K
Snippets
68
Records
86
Agent score
72%

What's inside Vuelidate

  1. Understand Vuelidate validation state structures

    Vuelidate utilizes two distinct structures: the validations component option, which defines the validation rules, and the v$ structure, which is an object in the Vue VM that holds the current validation state. The v$ structure follows the shape of the validations definition but adds reserved state properties (starting with $) that cannot be used as custom validator names.
  2. Access validator parameters and paths

    For advanced error rendering or internationalization, Vuelidate provides metadata about the validation structure:

    • $params (Object): Contains the types and parameters of all validators at the current level (including those declared via withParams) and child validation groups.
    • $path (String): The dot-notation nested path of the current form leaf.
  3. Implement asynchronous validators

    Validators that return a Promise must be wrapped in the helpers.withAsync helper to enable pending status tracking and response storage.
    import { helpers } from '@vuelidate/validators'
    const { withAsync } = helpers
    
    export default {
      data () { return { foo: '' } },
      validations: {
        foo: { asyncValidator: withAsync(asyncValidator) }
      }
    }
  4. Define custom error messages for validators

    Use the helpers.withMessage helper to override default error messages. The message can be a static string or a reactive function receiving $invalid, $model, $params, and $pending.
    import { required, helpers, minLength } from '@vuelidate/validators'
    
    const validations = {
      name: {
        // Static message
        required: helpers.withMessage('This field cannot be empty', required),
        
        // Reactive message function
        minLength: helpers.withMessage(
          ({ $pending, $invalid, $params, $model }) => 
            `This field has a value of '${$model}' but must have a min length of ${$params.min} so it is ${$invalid ? 'invalid' : 'valid'}`,
          minLength(4)
        )
      }
    }
  5. Define basic validation rules in Vuelidate

    Validation rules are defined within a validations method in the component. Each rule must have a corresponding property in the component's data object. Validators are functions that return true (or { $valid: true }) if validation passes, and false otherwise. Built-in validators from @vuelidate/validators provide additional properties like $validator, $message, and $params.
    import { useVuelidate } from '@vuelidate/core'
    import { required } from '@vuelidate/validators'
    
    export default {
      setup () {
        return {
          v$: useVuelidate()
        }
      },
      data () {
        return {
          name: ''
        }
      },
      validations () {
        return {
          name: { required }
        }
      }
    }
  6. Create a validation collector-only component

    A collector-only component is a top-level component in a validation chain used primarily to display error messages. It does not have its own state or validation rules. You can create one by calling useVuelidate without parameters or by passing only a configuration object.
    // Basic collector
    export default {
      setup: () => ({ v: useVuelidate() })
    }
    
    // Collector with specific configuration
    export default {
      setup: () => ({ v$: useVuelidate({ $stopPropagation: true, $scope: 'foo' }) })
    }
  7. Handle optional fields in custom validators

    By default, a custom validator returns false for empty inputs. To make a validator ignore empty fields (making the field optional), use the helpers.req helper to check if the value is present before applying the validation logic.
    import { helpers } from '@vuelidate/validators'
    
    const mustBeCool = (value) => !helpers.req(value) || value.includes('cool')
  8. Create parameterized custom validators

    To create a validator that accepts arguments, use a higher-order function that returns the actual validator function.
    import { helpers } from '@vuelidate/validators'
    
    const contains = (param) => (value) =>
      !helpers.req(value) || value.includes(param)
    
    // Usage in validations object:
    myField: {
      mustBeCool: contains('cool')
    }
  9. Add reactive dependencies to async validators

    If an async validator depends on other reactive properties, pass those dependencies as the second parameter to withAsync. This can be a single ref, an array of refs, a getter function, or a computed property.
    import { helpers } from '@vuelidate/validators'
    const { withAsync } = helpers
    
    const foo = ref('')
    const bar = ref(false)
    const store = reactive({ foo: '' })
    
    function validator (value) {
      if (foo.value === 'foo') return false
      return value === 'bar'
    }
    
    // Single ref dependency
    const asyncVal1 = withAsync(validator, foo)
    
    // Multiple ref dependencies
    const asyncVal2 = withAsync(validator, [foo, bar])
    
    // Reactive property via getter or computed
    const asyncVal3 = withAsync(validator, () => store.foo)
  10. Create a dynamic validation schema

    Because validations can be defined as a function or a computed property, the schema can change dynamically based on the model's data. Vuelidate automatically re-computes the schema and preserves the $dirty state of properties even if they are temporarily removed from the tree.
    // Composition API Example
    const rules = computed(() => {
      const localRules = { shippingAddress: { required } }
      if (!state.billingSameAsShipping) {
        localRules.billingAddress = { required }
      }
      return localRules
    })
    const v$ = useVuelidate(rules, state)
  11. Return extra data from custom validators

    Validators can return an object instead of a boolean to provide detailed error information. The object must contain a $valid key. The entire response object is accessible via the $response property on the validation and error objects, which can be used for custom error messages or metadata.
    // Validator returning extra data
    function validator (value) {
      if (value === 'something') return { $valid: true }
      return {
        $valid: false,
        message: 'The value must be "something"',
        extraParams: {}
      }
    }
    
    // Using the response in withMessage
    const validatorWithMessage = withMessage(({ $response }) => $response?.message || 'Invalid Data', validator)
    
    // Accessing response data in a computed property
    computed: {
      someComputed () {
        const params = this.v$.name.validatorName.$response
      }
    }
    
  12. Handle server-side validation with $externalResults

    The $externalResults configuration allows you to inject validation messages from external sources (like a server API). Each property in the state can be mapped to a string or an array of strings containing error messages.
    // Composition API Example
    const state = reactive({ foo: '' });
    const $externalResults = ref({});
    const rules = { foo: { someValidation } };
    const v = useVuelidate(rules, state, { $externalResults });
    
    async function validate () {
      if (!await v.value.$validate()) return;
      const errors = { foo: ['Error one', 'Error Two'] };
      $externalResults.value = errors;
    }
    
    // Options API Example
    export default {
      data () {
        return {
          foo: '',
          vuelidateExternalResults: { foo: [] }
        }
      },
      methods: {
        validate () {
          const errors = { foo: ['Error one', 'Error Two'] };
          Object.assign(this.vuelidateExternalResults, errors);
        }
      }
    }