Skip to main content

Function signature

function validate(
  schema: SimpleValidationSchema,
  data: Record<string, any>,
  options: ValidationOptions
): string[]
Validates data according to the specified schema and returns an array of error messages. Returns an empty array if validation succeeds.

Parameters

schema
SimpleValidationSchema
required
The validation schema that defines the structure and rules for your data. See SimpleValidationSchema for details.
data
Record<string, any>
required
The data object to validate. Each key should correspond to a field defined in the schema.
options
ValidationOptions
required
Validation options including language and custom error messages. See ValidationOptions for details.

Returns

errors
string[]
An array of error messages. Each error is formatted as "FieldName: error message". Returns an empty array if validation succeeds.

Examples

Basic validation

import { validate } from 'polyval';

const schema = {
  email: {
    type: 'string',
    required: true,
    email: true
  },
  age: {
    type: 'number',
    required: true,
    min: 18
  }
};

const data = {
  email: '[email protected]',
  age: 25
};

const errors = validate(schema, data, { lang: 'en' });
console.log(errors); // []

Validation with errors

const data = {
  email: 'invalid-email',
  age: 15
};

const errors = validate(schema, data, { lang: 'en' });
console.log(errors);
// [
//   "Email: Must be a valid email address",
//   "Age: Must be at least 18"
// ]

Validation with custom messages

const errors = validate(schema, data, {
  lang: 'en',
  customMessages: {
    required: 'This field is mandatory',
    string: {
      email: 'Please enter a valid email address'
    },
    number: {
      min: (min) => `You must be at least ${min} years old`
    }
  }
});
The validate function automatically formats field names by capitalizing the first letter in error messages.

Error handling

If an unexpected error occurs during validation, the function returns a single-element array:
['An unexpected validation error occurred']
The validate function catches all exceptions and returns a generic error message. Check the returned array to determine if validation succeeded (empty array) or failed (non-empty array).

Build docs developers (and LLMs) love