logo dile-components dile-components

Validating data without a form

The Validator class validates plain objects, for example in tests or in components that are not forms:

import { Validator } from '@dile/validation';

const validator = new Validator({ language: 'es' });
const { valid, errors } = await validator.validate(
  { email: 'ana@example', age: '12' },
  { email: 'required|email', age: 'integer|min:18' },
);
// errors: { email: 'Introduce un email vĂ¡lido.', age: 'El valor debe ser 18 o mayor.' }

validator.validateValue(value, rules, context) validates a single value and returns the message, or ''.

The rules, the messages and the languages are the same as in the forms: see the Rules reference and Messages and languages. Conditional rules with when work too.