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().

Validating a request body
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.

Error response format
{
  "errors": {
    "title": ["title must be at least 3 characters"],
    "email": ["email must be a valid email"],
    "age": ["age is required"]
  }
}
Reading the result
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.

required

Must be present and not empty

optional

Skips the remaining rules when empty

string

Must be a string

numeric

Must be a number or numeric string

integer

Must be a whole number

boolean

Must be true or false

array

Must be an array

email

Must be a valid email address

url

Must 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

alpha

Letters only

alphanumeric

Letters and numbers only

date

Must 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.

Optional fields
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(...).

Unique
// 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)]
Exists
// 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.

A custom rule
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]
})
An async rule
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.

Using the full payload
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.

rule(validator, message)
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.

A message built from the value
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.

Validate the nested object separately
// 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]
})
Or flatten first
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]
  }
)