Projects

v-valid

Model-based form validation made for Vue 3 with an extensible API

View / Source
Type

library

Active

2022 - 2026

Status

Done

Tags

Library, Form Validation, TypeScript

Projects
v-validlibrary2022 - 2026View / Source

Model-based validation library heavily inspired by Vuelidate, written for Vue 3 and mainly used for validation of user inputs but also as a simple data validation tool.

It works by passing a reactive object and a rule object into a composable. This composable provides a few control methods as well as an errors object.

How it’s used

// Example.vue

interface Form {
  name: string
  meta: {
    age: number
    gender?: any
  }
}

// Prepare empty reactive form
const form = reactive<Form>({
  name: '',
  meta: {
    age: 0,
    gender: undefined
  }
})

// Rules object
// Its keys and structure must match with the original form
const rules = {
  name: {
    required, // Input is required
    minLength: minLength(3), // Minimum input length is 3
  },
  meta: {
    age: {
      required,
      number, // Input must be a number
      between: between(3, 99) // A number that must fall between 3 and 99
    }
  }
}

// We can provide a type, which will let us know if we forgot to validate
// any required parameters
const { validate, reset, errors } = useValidation<Form>(
  form,
  rules,
  { autoclear: true }
)

Running the validate() method triggers the validation process. It iterates over each field in the form and matches it against an available rule field. If something does not match, the promise will be rejected and contain the generated errors object.

// Called when submitting a form
function submit(e) {
  e.preventDefault()

  validate()
    .then(() => {
      // Runs when validation passes
    })
    .catch((e) => {
      // Runs when validation fails, exposes the error object
    })
}
// Optionally, we can provide a field or a list of fields to validate only
validate('name')
validate(['name', 'age'])

Error object

Compared to Vuelidate, the errors object is very simple because I found myself not needing most of the other available fields. And it made working with the original library a little cumbersome. It only consists of four fields.

export interface Error {
  // The field name that corresponds to the form property
  id: string
  // The value it received from the form object
  value: any
  // Whether it was valid or not
  invalid: boolean
  // Contains all the failed rule keys and their error messages
  errors: Record<string, string>
}

Helpers

Sometimes creating a simple rule object is not enough. For instance, we have a list of rules but only need one of them to pass or we want to add a custom message to the error. All helpers

Custom rules
// Define a simple rule without parameters
const helloWorldRule = $def((value) => {
  // Return a boolean or Promise<boolean>
  return value === 'Hello World'
}, 'You have to write Hello World')

// Usage
const rules = {
  property: {
    helloWorldRule
  }
}
// Define a rule with parameters
const myCustomBetweenRule = $defParam(
  // First parameter is the value
  // Afterwards we can supply as many parameters as we want
  (value, min, max) => {
    if (typeof value !== 'number')
      return false

    return value >= min && value <= max
  },
  // Label can also be a function, which mimics the rule definition syntax
  (value, min, max) => {
    return `Value (${value}) must be between ${min} and ${max}.`
  }
)
Grouping rules
const rules = {
  rule: {
    // Passes if all the provided rules do not fail
    andOperator: and(type.str, type.num, minLength(10)),
    // Passes if at least one of these rules does not fail
    orOperator: or(type.map, type.arr, type.set),
    // Passes if all the provided rules fail
    notOperator: not(hasSpecialChars, url)
  }
}
Custom label
const rules = {
  rule: {
    regex: withLabel(
      'No spaces allowed',
      match(/^\S*$/)
    )
  }
}

Footnote

If you’re interested in how this project was made, you can visit the GitHub repository, which includes the source code and full documentation. I am always open to contributions or feedback!