Skip to content

validate()

const { validate } = require('kaelum/validate');

This is a subpath export — it does not come from the main kaelum package. Import it explicitly only when needed.

validate(schema)
NameTypeDescription
schemaObjectValidation schema. Accepts body, query, and/or params keys.
schema.bodyObjectRules for req.body fields.
schema.queryObjectRules for req.query fields. Values are coerced before validation.
schema.paramsObjectRules for req.params fields. Values are coerced before validation.

Each key in a target object is a field name. Its value is a rules object:

RuleTypeDescription
type'string' | 'number' | 'boolean' | 'array' | 'object'Expected type
requiredbooleanField must be present and non-empty
minnumberString: min chars. Number: min value. Array: min items
maxnumberString: max chars. Number: max value. Array: max items
patternstring | RegExpPreset name or custom RegExp (strings only)
custom(value) => true | stringCustom function — return true to pass
PresetValidates
'email'user@domain.tld
'url'http(s)://...
'uuid'Standard UUID v4
'alphanumeric'Letters and digits only

An Express RequestHandler (middleware function).

  • On failure: Responds 400 with { error: "Validation failed", fields: [...] }. All field errors are collected before responding.
  • On success: Calls next().
// Basic usage
validate({
body: {
name: { type: 'string', required: true, min: 2 },
email: { type: 'string', required: true, pattern: 'email' },
},
});
// Validate query params with type coercion
validate({
query: {
page: { type: 'number', min: 1 },
limit: { type: 'number', max: 100 },
},
});
// Custom validator
validate({
body: {
score: {
type: 'number',
custom: (v) => v % 2 === 0 || 'Score must be even',
},
},
});