Validation
Request validation with built-in rules
Basic Usage
Validate request data with the validate function and the built-in rules. It returns a result object — check it with fails() or passes().
import { validate, rules } from '@basicbenframework/core/validation'
export const store = async (req, res) => {
const result = await validate(req.body, {
title: [rules.required, rules.min(3), rules.max(100)],
email: [rules.required, rules.email],
age: [rules.required, rules.numeric, rules.min(18)]
})
if (result.fails()) {
return res.json({ errors: result.errors }, 422)
}
// Data is valid, continue...
}Validation stops at the first failing rule for each field, so every field has at most one message. Messages interpolate the field name as written in the schema.
{
"errors": {
"title": ["title must be at least 3 characters"],
"email": ["email must be a valid email"],
"age": ["age is required"]
}
}result.fails() // true if any field failed
result.passes() // the inverse
result.errors // { field: [message] }
result.first('email') // first message for a field, or null
result.all() // [{ field, message }, ...]Available Rules
Note that min and max cover both cases: they compare length for strings and value for numbers.
requiredMust be present and not empty
optionalSkips the remaining rules when empty
stringMust be a string
numericMust be a number or numeric string
integerMust be a whole number
booleanMust be true or false
arrayMust be an array
emailMust be a valid email address
urlMust be a valid URL
min(n)String at least n characters, or number at least n
max(n)String at most n characters, or number at most n
between(a, b)Number within a and b, inclusive
length(n)String exactly n characters
in(...values)Must be one of the given values
notIn(...values)Must not be one of the given values
regex(pattern)Must match the pattern
alphaLetters only
alphanumericLetters and numbers only
dateMust be a parseable date
before(date)Date earlier than the given date
after(date)Date later than the given date
confirmed(field)Must match another field, e.g. password
different(field)Must differ from another field
unique(table, col?, exceptId?)No such row in the database
exists(table, col?)A matching row exists in the database
Optional Fields
Rules ignore empty values, so a field without required is already optional — the other rules only apply once it has a value. Add rules.optionalfirst when you want to stop the chain outright for an empty field.
const result = await validate(req.body, {
name: [rules.required], // must be present
bio: [rules.max(500)], // optional; if present, at most 500 characters
website: [rules.url], // optional; if present, must be a URL
nickname: [rules.optional, rules.min(2)]
})Database Rules
unique and exists query the database, so they are async — remember to await validate(...).
// No other user has this email
email: [rules.required, rules.email, rules.unique('users')]
// Check a specific column
slug: [rules.unique('categories', 'slug')]
// Ignore the record being updated
email: [rules.unique('users', 'email', currentUserId)]// The referenced user must exist
user_id: [rules.required, rules.exists('users')]
// Match on a specific column
category: [rules.exists('categories', 'slug')]Custom Rules
A rule is a function receiving (value, field, data). Return a message to fail, or null to pass. Rules may be async.
const isSlug = (value, field) => {
if (!/^[a-z0-9-]+$/.test(value)) {
return `${field} must contain only lowercase letters, numbers and hyphens`
}
return null
}
const result = await validate(req.body, {
slug: [rules.required, isSlug]
})const isAvailableUsername = async (value) => {
const existing = await (await db.table('users'))
.where('username', value)
.first()
return existing ? 'Username is already taken' : null
}
const result = await validate(req.body, {
username: [rules.required, isAvailableUsername]
})The third argument is the whole payload, which is how a rule can compare fields.
const afterStart = (value, field, data) => {
if (new Date(value) <= new Date(data.starts_at)) {
return `${field} must be after starts_at`
}
return null
}Custom Error Messages
Wrap a check with the rule helper to supply your own message. The validator it wraps signals failure by returning false.
import { validate, rules, rule } from '@basicbenframework/core/validation'
const result = await validate(req.body, {
email: [
rule((value) => !!value, 'Please enter your email'),
rule((value) => /.+@.+\..+/.test(value), 'Please enter a valid email address')
],
password: [
rule((value) => (value || '').length >= 8, 'Password must be at least 8 characters')
]
})The message may also be a function of (field, value), which is useful when it should mention what was submitted.
rule(
(value) => (value || '').length <= 100,
(field, value) => `${field} is ${value.length} characters; the limit is 100`
)Nested Data
Schema keys are looked up directly on the object, so dot notation like'user.name' does not resolve into a nested object. Validate the nested object on its own, or pull the values up first.
// Request body: { user: { name: 'Ada', email: '[email protected]' } }
const result = await validate(req.body.user ?? {}, {
name: [rules.required, rules.min(2)],
email: [rules.required, rules.email]
})const result = await validate(
{ name: req.body.user?.name, email: req.body.user?.email },
{
name: [rules.required, rules.min(2)],
email: [rules.required, rules.email]
}
)