Skip to main content

createValidationRules

The createValidationRules function takes a configuration object and returns a function that uses your configuration to validate an object. The returned function is small wrapper around the validatorjs libraries Validator constructor that abstracts away running the .passes() method and extracts the errors for you automatically.

Types

export type ValidatorError = {
key?: string;
type?: 'inline' | 'global';
title?: string;
message: string;
} | null;

export type ValidationRule = Partial<NonNullable<ValidatorError>> & {
rule: string | ((values: any, helpers: any) => string | null);
};

export type Definition = {
name?: string;
rules: string | (ValidationRule | string)[];
};

export type CreateValidationRulesArgs = {
messages?: { [key: string]: string };
definitions: { [key: string]: Definition };
};

Messages

The messages argument contains all of the custom messages for each different validation type. These will be applied on a global level but can be overridden by more specific custom messages on a per-property basis as part of the definitions argument.

The template string :attribute will be replaced by the property name when an error is created.

const messages = {
required: 'This :attribute field is required'
};

Definitions

The definitions argument is the configuration for each property in the object that is undergoing validation. For nested properties the key for the definition will be a string separating each nested section with a period. Wildcard characters (denoted by *) can be used to make sure field arrays have the same validation.

Each definition has an optional name property, and a required rules property. The createValidationRules function will try to turn the property name into something that is more user-friendly (e.g. turning periods or underscores into spaces) however if this doesn't work or doesn't make sense then the name can be defined and it will be used instead.

import { createValidationRules } from '@rexlabs/validator';

// Object of values to be validated
const obj = {
first_name: 'Obi-wan',
address: {
galaxy: '',
sector: 'Delta-5',
planet: 'Tatooine'
},
phone: ['555-0123', '555-9999']
};

const definitions = {
first_name: {
rules: ['required', 'min:2']
},
'address.galaxy': {
name: 'galaxy',
rules: 'required'
},
'address.planet': {
name: 'planet',
rules: 'required'
},
'phone.*': {
name: 'phone number',
rules: 'required'
}
};

const validator = createValidationRules({ messages, definitions });