validate-this
validate-this
is a validation library that applies validation rules to structured form data. It also allows you to define your own validation rules.
Validating Form Data
Imagining that we have structured form data that looks like:
const formData = username: '' email: 'bob'
Then we could pass that object into the function below:
{ return }
Calling the function with the formData
we defined previously will return an errors
object like this:
username: 'required' email: 'email_invalid'
Defining a Custom Validation
There are two ways to do your own validations: by using the satisfies
validation,
or by using defineValidator
.
.satisfies(...rules)
Call this with your own validation rule(s). Example:
{ if value && !email return 'email_invalid' } { return }
Or with multiple rules:
{ return { if value <= n return 'too_small' }} { return { if value >= n return 'too_big' }} { return }
defineValidator(config)
In the most simple case, a rule accepts a value
and returns a string if and only if the value
is invalid.
For more complex cases, a higher order rule can be defined. The example below is built into
validate-this
but makes a good demonstration.
This will validate that one field matches another. Here's a validation function that uses this validator:
{ return }
Deep Validation
If your form data is like this instead:
const formData = name: 'Bob' address: street: '123 Fake St'
Then you can validate the address
property like this:
{ return }
Or if there's a nested array:
const formData = contacts: name: 'bob' email: 'bob@example.com'
Then you can validate those like this:
{ return }
Message translation
A third argument can be provided to the validator
function that will allow you to
translate error messages using something like I18n
. Example:
{ return }