Skip to content

Custom validation methods

You can add custom validation method inline by using custom name inside validation schema or pass custom validator inside options.validators object.

Inline

custom could be function or array of fuctions if you need multiple custom validators.

js
import { validate } from '@hiperf/validate';

const schema = {
	message: {
		custom(v) {
			const errors = [];

			if (!/🐈|😺|😸|😻|😽/.test(v))
				errors.push('Message should contain cat emoji! 😾');

			return errors;
		}
	}
};

const data = {
	message: '🐶 woof!'
};

const { isValid, errors } = validate(schema, data);
// isValid = false
// errors = ['Message should contain cat emoji! 😾']

Inline (multiple)

Multiple custom validators example.

js
import { validate } from '@hiperf/validate';

const schema = {
	message: {
		custom: [
			(v) => [
				!/🐈|😺|😸|😻|😽/.test(v) ? 
				'Message should contain cat emoji! 😾' : ''
			],
			(v) => [
				!/🐛|🐝|🐞|🐜|🦗/.test(v) ? 
				'Message should contain at less one bug! 🐸' : ''
			],
		]
	}
};

const data = {
	message: '🐶 woof!'
};

const { isValid, errors } = validate(schema, data);
// isValid = false
// errors = [
//     'Message should contain cat emoji! 😾',
//     'Message should contain at less one bug! 🐸'
// ]

TIP

If you return empty string, null, false or 0 inside errors array, and that value will not count as error.

Custom validators

You can also pass custom validator method to options.validators.

js
import { validate } from '@hiperf/validate';

const validators = {
	isCatMessage: v => /🐈|😺|😸|😻|😽/.test(v)
};

const locales = {
	en: { 'isCatMessage': 'Message should contain cat emoji! 😾' },
	es: { 'isCatMessage': 'El mensaje debe contener emoji de gato.! 😾' },
};

const schema = {
	message: {
		isCatMessage: true,
	}
};

const data = {
	message: '🐶 woof!'
};

const { isValid, errors } = validate(schema, data, { lang: 'es', validators, locales });
// isValid = false
// errors = ['El mensaje debe contener emoji de gato.! 😾']

INFO

Default lang is en, and it's used if you do not specify one inside options object.