# Validations
Validations are a central part of Loveform. The type of the Validation
functions is as follows:
type Validation<T> = (value: T) => true | string;
Here the T
generic parameter corresponds to the type of the field being validated. For instance, validations for LInput
and LTextarea
receive a string
value:
type Validation = (value: string) => true | string;
On the other hand, validations for LCheckboxGroup
receive an array of boolean
values:
type Validation = (value: Array<boolean>) => true | string;
# Indicating an error
Notice that validation functions return either true
or a string. Returning true
indicates that the validation passed. Returning a string indicates that the validation failed. The string returned by the validation function corresponds to the human-readable representation of the error.
The nice thing about this schema is that validation functions are very expressive. For instance, if you wanted to check that a string contains a &
character, the validation function would look like this:
(text: string) => text.includes('&') || 'The text must include a "&" character'
# Validation order
Validations are passed as arrays of multiple validation functions to validatable components. This means that you will probably have an array that looks something like this:
const validations = [
(text: string) => !!text.trim() || 'The text must not be empty',
(text: string) => text.includes('&') || 'The text must include a "&" character',
];
Here, the first validation run will be the first element in the array. Then the following validation will run and so on until the last validation function of the array. The first validation to fail will be the one to be shown to the user.
# Complex validations
Notice that, until now, the documentation has only shown validation functions with the following form:
(content) => validate(content) || 'error message'
But it could happen that your validation is much more complex than that. That should be no problem at all, as long as you always return true
when the validation passes or a string if the validation fails:
const validate = (content: string) => {
// run the validations here
if (validations === 'pass') {
return true;
}
return errorString;
}
const validations = [
...,
validate,
...,
];