Skip to content
This repository was archived by the owner on Jan 9, 2022. It is now read-only.

Documentation

jens edited this page Oct 23, 2021 · 63 revisions

Getting Started

Install vue3-form-validation with your favorite package manager:

yarn add vue3-form-validation
# or with npm
npm install vue3-form-validation

Configure the validation through createValidation and pass it to the app:

import { createValidation } from 'vue3-form-validation'

const validation = createValidation({
  defaultValidationBehavior: 'lazier',
  validationBehavior: {}
})

app.use(validation)

Start using useValidation in your components.

API

At its core, this package exports one function useValidation, plus some type definitions for when using TypeScript.

import { useValidation } from 'vue3-form-validation'

const {
  form,
  submitting,
  validating,
  errors,
  hasError,
  validateFields,
  resetFields,
  add,
  remove
} = useValidation({})

useValidation takes the following parameters

  • formData {object} The structure of your formData

FormData has a structure that is similar to any other object you would write for v-model data binding. The only difference being that together with every property, you can provide rules to display validation errors. Let's look at an example:

const formData = {
  email: '',
  password: ''
}

The above can be converted to the following:

const formData = {
  email: {
    $value: '',
    $rules: [email => !email && 'Please enter your email address']
  },
  password: {
    $value: '',
    $rules: [
      password =>
        password.length > 7 || 'Password has to be longer than 7 characters'
    ]
  }
}

FormData can contain arrays and can be deeply nested. At the leaf level, the object should contain fields whose simplified type definition looks like the following:

type Field<T> = {
  $value: T | Ref<T>
  $rules?: Rule<T>[]
}

useValidation exposes the following state

  • form {object} A transformed formData object
  • submitting {Ref<boolean>} True during validation after calling validateFields when there were rules that returned a Promise
  • validating {ComputedRef<boolean>} True while the form has any pending rules
  • errors {ComputedRef<string[]>} All current validation error messages
  • hasError {ComputedRef<boolean>} True if the form has any error

Form is a reactive object with identical structure as the formData input but with added metadata to every field. All objects with a $value are converted to an object of the following type:

type TransformedField<T> = {
  $uid: number
  $value: T
  $errors: string[]
  $rawErrors: (string | null)[]
  $hasError: boolean
  $validating: boolean
  $touched: boolean
  $dirty: boolean
  $validate(options?: ValidateOptions): void
}

Given the data of the previous example, this would result in the structure below:

type Form = {
  email: TransformedField<string>
  password: TransformedField<string>
}

Listed as follows are descriptions of all the properties and their use case:

  • $uid {number} The unique id of this field. For dynamic forms, this can be used as the key attribute in v-for
  • $value {any} The current field's value. Intended to be used together with v-model
  • $errors {string[]} A list of validation error messages local to this field without null values
  • $rawErrors {(string | null)[]} The field's raw error messages one for each rule and null if there is no error
  • $hasError {boolean} True while there are any errors on this field
  • $validating {boolean} True while the field has any pending rules
  • $touched {boolean} True if the field is touched. In most cases, this value should be set together with the blur event. Either through $validate or manually
  • $dirty {boolean} True if the $value of this field has changed at least once
  • $validate {function} Validate this field

$validate([options])

Validate the rules of this field.

  • options {object} Options to use for validation
    • setTouched {boolean} Set the field touched when called
      • Default
        true
    • force {boolean} Validate with the force flag set
      • Default
        true
  • Returns: {void}

useValidation exposes the following methods

validateFields([options])

Validate all fields.

  • options {object} Options to use for validation.
    • names {string[]} A list of field names to validate. Names are taken from the properties in the formData
      • Default
        undefined
        Meaning validate all
    • predicate {function} A filter function to determine which values to keep in the resulting formData. Used like Array.prototype.filter but for objects
      • Default
        () => true
        Meaning keep all
  • Returns: {Promise} A Promise containing the resulting formData
  • Throws: {Error} An Error of type ValidationError when there were any failing rules

predicate([iteratorResult])

  • iteratorResult {object}
    • key {string} The current key
    • value {any} The current value
    • path {string[]} The current path in the object
  • Returns: {any} Return true if the value should be kept

resetFields([formData])

Reset all fields to their default value or pass an object to set specific values.

  • formData { object } FormData to set specific values. It has the same structure as the object passed to useValidation
    • Default
      undefined
      Meaning use the default values

Remarks

It will not create any new fields that are not present in the formData initially.

add(path, value)

Adds a new properties to the formData.

  • path {(string | number)[]} A path where the new data is added
  • value {any} The data to add

Remarks

Objects with a $value property are transformed, as seen above.

remove(path)

Removes a property from the formData.

  • path {(string | number)[]} The path to the property to remove

Writing Rules

Clone this wiki locally