Skip to content

FormValidator

Yousif Al-Raheem edited this page Feb 12, 2020 · 2 revisions

Validate any form model. To use it, construct a new FormValidator.

Basic usage

const formValidator = new FormValidator<MyInterface>(obj)
    .addValidation(["firstname"], "required")
    .addValidation(["birthdate"], "isDate")
    .addValidation(["password"], "strongPassword")
    .validate();

and then you can use the output error object with any library framework you like. And then use formValidator.getErrors() to retrieve the errors.

This utility consists of the following methods:


Method: addValidation

Add validation criteria

Example

formValidator.addValidation(["firstname"], "required");

Properties

Param Type Description
fields Array<keyof T> The fields that the criteria will be added to. It's of type keyof of the interface passed
type ValidationType The type of validation to be executed. Note that this affects the required properties passed in the next parameter specs
specs? ValidationSpecs The specifications of the criteria

Validation types

The type of validation to be executed against the specified fields. You can find the list of supported validation types defined in the list below.

Validation type Description
"required" Mandatory field
"isDate" Field should be a date object
"validEmail" The field is a valid email address
"strongPassword" The field is a strong password
"isPhoneNumber" The field is a valid phone number
"dateRange" The field is a date object that matches a date range
IMPORTANT: Must pass either or both of minDate or maxDate in the specs
"valueRange" The field is a number matches a value range
IMPORTANT: Must pass either or both of minValue or maxValue in the specs
"textLength" The field is a string with a length that matches a length
IMPORTANT: Must pass either or both of minLength or maxLength in the specs

Validation specs

Validation specifications are required by some validation types. For example, to validate a string value is less than n characters long the validator needs to know the value of n. You can find the list of supported validation specs defined in the list below. However, when defining a custom validation you might want to add a new validation spec. You can read more about adding a custom validation.

Validation spec type Description
minLength number Minimum string length
maxLength number Maximum string length
minValue number Minimum number value
maxValue number Maximum number value
minDate Date Minimum date
maxDate Date Maximum date

Method: addCustomValidation

Add custom validation criteria

Example

/** Validating if `amount2` is bigger than `amount1` */
const validator = new FormValidator<ObjInterface>(obj).addCustomValidation(
    ["amount1", "amount2"],
    ["amount2"],
    () => {
        if (amount2 > amount1) {
            return {
                errorCode: "moreThanMaxValue", // One of many predefined error types
                specs: { maxValue: obj.amount1 }
            };
        } else {
            return null;
        }
    }
);

Properties

Param Type Description
errorFields Array<keyof T> The field(s) where the error will be displayed in
validator () => ModelFieldError The custom validation method that returns an error object of type ModelFieldError

Validation Errors

Validation Error Description
"empty" The field is empty
"invalidDate" The value is not a valid date object
"invalidEmail" The value is not a valid email address
"weakPassword" The value is a weak password
"beforeMinDate" The date occurred before the minimum date specified in the specs (minDate)
"afterMaxDate" The date occurred after the maximum date specified in the specs (maxDate)
"lessThanMinLength" The length of the string value is less than the minimum length specified in the specs (minLength)
"moreThanMaxLength" The length of the string value exceeds the maximum length specified in the specs (maxLength)
"lessThanMinValue" The numeric value is less than the minimum value specified in the specs (minValue)
"moreThanMaxValue" The numeric value exceeds the minimum value specified in the specs (maxValue)
"invalidInput" The value is invalid. This is a general error especially triggered when running type-specific validations such as string minimum length.
"invalidPhoneNumber" The value is an invalid phone number

Custom validation error and specs

When defining a custom validator you might want to create a new validation error or spec so it can be identified when reteiving the errors detected. To do so, just pass the custom error type when declaring a custom validation. See the example below:

type ExtraValidationSpecs = { dependencyValue: number };
type ExtraValidationErrors = "moreThanDependencyValue";

validator.addCustomValidation(
    ["dateB"],
    (): ModelFieldError<ExtraValidationErrors, ExtraValidationSpecs> => {
        if (model.withdrawAmount > model.balance) {
            return {
                errorCode: "moreThanDependencyValue",
                specs: { dependencyValue: model.balance }
            };
        } else {
            return null;
        }
    }
);

When you retrieve the error from the validator you can enable IntelliSense when you define the returned value like this:

const errors: ModelFieldError<
    ExtraValidationErrors,
    ExtraValidationSpecs
> = validator.getErrors();

Method: validate

Initiate the validation process after all validation criteria have been added and ready to be validated. validator.validate()


Method: getErrors

Retreive the validation result as an object that resembles the original model. For example:

const validator = new FormValidator<{ first: string, second: number }>(model).validate().getErrors();
/** This returns the following:
 * {
 *     first: {}, // validation result of type ModelFieldError 
 *     second: {}, // validation result of type ModelFieldError 
 * }
 */

Method: getError

Retreive the validation result of a single field of the model. The returned value is an object of type ModelFieldError.

Properties

Param Type Description
name keyof T The name of the field to retrieve