Skip to content

Validation ​

Introduction ​

Almost every request carries data you cannot trust. The @plinthjs/validation package checks that data against rules and collects readable error messages. You can use it in two ways: as a standalone Validator for any object, or through the validate(request, rules) helper that ties it to an HTTP request and turns failures into the right response for browsers and API clients.

bash
pnpm add @plinthjs/validation

Quick Start ​

In a controller, call validate with the request and a map of field names to rules. If everything passes you get back the validated data. If something fails, it throws, and the framework's exception handler turns the failure into a response (described in How Failures Are Rendered), so you do not need a try/catch.

ts
import { validate } from '@plinthjs/validation'

import type { Request, Response } from '@plinthjs/http'

export class RegisteredUserController {
  async store(request: Request): Promise<Response> {
    const data = await validate(request, {
      name: 'required|string|max:255',
      email: 'required|email|max:255',
      password: 'required|string|min:8|confirmed',
    })

    // data => { name: '...', email: '...', password: '...' }
    // password_confirmation and any other input is not included.
    return Response.json({ created: data.name })
  }
}

validate reads the merged input of the request (query string, form fields and JSON body) and returns only the fields that had rules. The generated application uses exactly this pattern in its login and registration controllers.

Writing Rules ​

Rules for one field are either a pipe-separated string or an array.

ts
'required|string|min:3|max:50'[('required', 'string', ['min', 3], ['max', 50])]

A rule that takes parameters uses a colon, with commas between parameters: between:18,120, in:draft,published. In array form, a tuple holds the rule name followed by its parameters: ['between', 18, 120]. The array form can also hold closures and rule objects, which are covered below.

Field names use dot notation for nested data (profile.age), and * matches every element of an array (see Validating Arrays).

An unknown rule name throws Unknown validation rule [name]. as soon as the validator runs, so a typo is a programmer error and not a silent pass.

The Validator ​

Without a request, create a validator yourself. Every method that runs the rules is asynchronous, because rules can be async.

ts
import { Validator } from '@plinthjs/validation'

const validator = Validator.make(
  { name: 'Al', email: 'nope', age: 'x' },
  { name: 'required|string|min:3', email: 'required|email', age: 'integer' },
)

await validator.passes() // => false
await validator.fails() // => true

const errors = await validator.errors()
errors.first('email') // => 'The email must be a valid email address.'

The rules run once. Calling passes(), fails() or errors() again reuses the result.

Retrieving the Validated Data ​

validated() (or its alias validate()) runs the rules and returns the data for the fields that had rules and passed. It throws a ValidationError when anything failed.

ts
const data = await Validator.make(
  { name: 'Ada', email: 'ada@example.com', password: 'secret1', password_confirmation: 'secret1' },
  { name: 'required|string|min:3', email: 'required|email', password: 'required|confirmed|min:6' },
).validated()
// => { name: 'Ada', email: 'ada@example.com', password: 'secret1' }

safe() wraps the same result in a ValidatedInput, which has all(), only(...keys), except(...keys) and merge(extra). Keys use dot notation.

ts
const safe = await Validator.make(
  { name: 'A', password: 'p', profile: { age: 20 } },
  { name: 'required', password: 'required', 'profile.age': 'integer' },
).safe()

safe.only('name', 'profile.age') // => { name: 'A', profile: { age: 20 } }
safe.except('password') // => { name: 'A', profile: { age: 20 } }
safe.merge({ role: 'member' }) // => { name: 'A', password: 'p', profile: { age: 20 }, role: 'member' }

A field appears in the validated data only if it passed and either was present in the input or had the required rule. A field marked sometimes that was absent is left out.

Available Rules ​

An empty value (null, undefined or '') skips every rule on a field except required and the other rules that decide whether a value is needed (the required_*, present*, missing*, filled and accepted families). Add nullable to be explicit that an empty value is acceptable.

Presence and Flow Control ​

RuleMeaning
requiredNot null or undefined, a string with non-blank content, and not an empty array
nullableAn empty value skips the remaining rules
sometimesIf the key is absent from the data, skip the field entirely
bailStop running this field's rules after its first failure
filledIf the key is present, its value must not be empty
presentThe key must exist, even if empty
missingThe key must not exist
prohibitedFails if the field has a value
excludeDrop the field from validation and from the validated data
ts
await Validator.make({ a: '' }, { a: 'required|string|min:3' }).errors() // 1 message: required
await Validator.make({ a: '' }, { a: 'bail|required|string|min:3' }).errors() // 1 message: required
await Validator.make({ a: null }, { a: 'nullable|string|min:3' }).passes() // => true

Types and Formats ​

string, integer, numeric, boolean (accepts true, false, 1, 0, '1', '0', 'true', 'false'), array, list, json.

email, url, active_url (the shape of an http or https URL, no network lookup), ip, ipv4, ipv6, mac_address, uuid (optionally uuid:4), ulid, hex_color, timezone.

alpha, alpha_dash, alpha_num accept Unicode letters by default. Add the ascii parameter to restrict them to ASCII (alpha:ascii). ascii itself, lowercase and uppercase check string content.

regex:/^[A-Z]{2}\d{2}$/ and not_regex take a pattern. Both a delimited literal with flags and a bare pattern are accepted, and the pattern may contain commas.

ts
await Validator.make({ code: 'AB12' }, { code: 'regex:/^[A-Z]{2}\\d{2}$/' }).passes() // => true

Size and Numbers ​

min, max, between and size measure the "size" of the value: the number itself for numbers, the length for strings, the element count for arrays and the size in kilobytes for uploaded files.

ts
const rules = {
  age: 'numeric|between:18,120', // the number itself
  bio: 'string|max:500', // 500 characters
  tags: 'array|min:1|max:5', // 1 to 5 elements
  photo: 'file|max:2048', // 2048 KB
}

gt, gte, lt, lte compare against another field if one exists at that path, or a number otherwise. multiple_of:5, decimal:2 (or decimal:2,4 for a range of places), digits:4, digits_between:4,6, min_digits, max_digits.

ts
await Validator.make({ qty: 5, max: 3 }, { qty: 'lte:max' }).errors()
// => { qty: ['The qty must be less than or equal to max.'] }

Membership and Comparison ​

in:a,b,c and not_in:a,b,c check against a list. same:other and different:other compare with another field. confirmed requires <field>_confirmation to equal the field, the usual pattern for passwords. in_array:other.* requires the value to appear among another field's values. starts_with, ends_with, doesnt_start_with, doesnt_end_with take a list of strings. contains and doesnt_contain check that an array holds (or lacks) values.

ts
await Validator.make({ a: 'x', b: 'x' }, { a: 'different:b' }).errors()
// => { a: ['The a and b must be different.'] }

Dates ​

date accepts ISO 8601 dates and datetimes, Y-m-d and the keywords now, today, tomorrow and yesterday. date_format:Y-m-d accepts one or more formats built from the tokens Y, m, d, H, i and s (other characters match literally). before, before_or_equal, after, after_or_equal and date_equals compare with a literal date or another field.

ts
await Validator.make(
  { start: '2024-01-05', end: '2024-01-01' },
  { start: 'date|after:2024-01-01', end: 'date_format:Y-m-d|before:start' },
).passes() // => true

Acceptance ​

accepted passes for yes, on, 1 and true; declined passes for no, off, 0 and false. Both have _if variants: accepted_if:other,value and declined_if:other,value.

ts
await Validator.make({ terms: 'no' }, { terms: 'accepted' }).errors()
// => { terms: ['The terms must be accepted.'] }

Distinct Values ​

distinct works on wildcard fields: within tags.*, no two elements may be equal. Use distinct:strict for strict equality or distinct:ignore_case.

ts
await Validator.make({ tags: ['a', 'a'] }, { 'tags.*': 'distinct' }).errors()
// => { 'tags.0': ['The tags.0 field has a duplicate value.'], 'tags.1': [...] }

Files ​

file, image, mimes:jpg,png, mimetypes:image/png, extensions:jpg,png and dimensions apply to uploaded files. The input only needs to look like a file (an object with getClientOriginalName, getClientOriginalExtension, getMimeType, getSize and get), which is what the uploaded files in @plinthjs/http provide. image and mimes look at the real bytes (JPEG, PNG, GIF, WebP and BMP are detected), so a renamed file does not pass. SVG is rejected by image unless you write image:allow_svg.

dimensions takes min_width, max_width, min_height, max_height, width, height and ratio as named parameters, for example dimensions:min_width=100,ratio=3/2. The fluent builder is usually easier to read, see Rule Builders.

Database Rules ​

exists:table,column requires a matching row and unique:table,column,exceptId,idColumn requires that no row matches. They need a presence verifier, covered under Database Rules.

Conditional Rules ​

Several rules make a field required, present, prohibited or excluded depending on the rest of the input. The first parameter is another field; the remaining parameters are the values to match.

RuleApplies when
required_if:field,value,...field equals one of the values
required_unless:field,value,...field does not equal any of the values
required_with:a,bany of the listed fields is present
required_with_all:a,ball of the listed fields are present
required_without:a,bany of the listed fields is not present
required_without_all:a,bnone of the listed fields is present
required_if_accepted:fieldfield is accepted
required_if_declined:fieldfield is declined
ts
await Validator.make({ type: 'company' }, { company: 'required_if:type,company' }).errors()
// => { company: ['The company field is required.'] }

await Validator.make(
  {},
  { email: 'required_without:phone', phone: 'required_without:email' },
).errors()
// => { email: ['The email field is required when phone is not present.'],
//      phone: ['The phone field is required when email is not present.'] }

The same shape exists for present_if, present_unless, present_with, present_with_all, missing_if, missing_unless, missing_with, missing_with_all, prohibited_if, prohibited_unless, prohibits:other (when this field is filled, the listed fields must be empty) and the exclude family: exclude_if, exclude_unless, exclude_with, exclude_without. A field removed by an exclude rule is not validated and does not appear in the validated data.

ts
await Validator.make(
  { a: 'x', b: 'y' },
  { a: 'required', b: 'exclude_if:a,x|required' },
).validated()
// => { a: 'x' }

Adding Rules Based on a Condition ​

sometimes(field, rules, condition) on a validator adds rules only when a callback over the input returns true.

ts
const validator = Validator.make({ a: 'x' }, { a: 'required' }).sometimes(
  'c',
  'required',
  (data) => data['a'] === 'x',
)
await validator.errors() // => { c: ['The c field is required.'] }

Inside a rules array, Rule.when(condition, rules, otherwise), Rule.unless(...), Rule.requiredIf(condition), Rule.excludeIf(condition) and Rule.prohibitedIf(condition) take a boolean or a function of the input:

ts
import { Rule } from '@plinthjs/validation'

Validator.make(
  { kind: 'x', n: 'abc' },
  { n: [Rule.when((data) => data['kind'] === 'x', 'integer', 'string')] },
)
// n must be an integer here, because kind is 'x'

Validating Arrays ​

Use * in a field name to apply rules to every element. Errors are reported against the concrete path of each failing element.

ts
const v = Validator.make(
  {
    items: [
      { name: 'a', qty: 1 },
      { name: '', qty: 'x' },
    ],
  },
  { 'items.*.name': 'required|string', 'items.*.qty': 'integer|min:1' },
)

;(await v.errors()).all()
// => { 'items.1.name': ['The items.1.name field is required.'],
//      'items.1.qty': ['The items.1.qty must be an integer.'] }

Rules that point at other fields stay inside the same array element. In items.*.confirm with same:items.*.value, the * is replaced by the index being checked, so row 2 is compared with row 2. The validated data keeps the array structure.

Custom Error Messages ​

Pass a third argument to Validator.make (or return it from a form request's messages()) to override text. A key is either field.rule, which wins, or a bare rule name that applies to every field.

ts
const errors = await Validator.make(
  { name: '', age: 2 },
  { name: 'required', age: 'min:18' },
  {
    'name.required': 'Please tell us your name.',
    min: ':attribute needs :min or more',
  },
).errors()

errors.all() // => { name: ['Please tell us your name.'], age: ['age needs 18 or more'] }

Messages can use these placeholders: :attribute (the field), :other (the other field a rule refers to), :value, :values (the parameters joined with commas), :min, :max, :size, :date, :digits, :decimal and :format. The default messages are English; the table of defaults is exported as defaultMessages.

INFO

By default :attribute is the field name exactly as it appears in the rules, such as email or items.1.name. For friendlier labels pass an attributes map as the fourth argument to Validator.make (or call setAttributeNames(); a FormRequest overrides attributes()). It applies to default and custom messages, and to :other:

ts
const validator = Validator.make(data, { email: 'required' }, {}, { email: 'email address' })
// "The email address field is required."

The default required_if and required_unless messages name the other field and values ("The company field is required when type is company."), like required_with does.

For translated messages, build the map from your localization files before creating the validator.

Custom Rules ​

Closure Rules ​

The simplest custom rule is a function. It receives the value and the full input and returns true to pass, or a string message to fail. It can be async.

ts
const slug = (value: unknown) => (/^[a-z-]+$/.test(String(value)) ? true : 'Bad slug.')

await Validator.make({ slug: 'Bad Slug' }, { slug: ['required', slug] }).errors()
// => { slug: ['Bad slug.'] }

await Validator.make(
  { b: 2, a: 5 },
  {
    b: [
      (value, data) =>
        Number(value) > Number((data as { a: number }).a) ? true : 'b must exceed a',
    ],
  },
).errors()
// => { b: ['b must exceed a'] }

An async closure is the way to run a database or network check:

ts
const available = async (value: unknown) =>
  (await usernameIsFree(String(value))) ? true : 'That username is taken.'

Validator.make(data, { username: ['required', available] })

Rule Objects ​

For a reusable rule, write an object with a validate(attribute, value, data) method returning true, a message, or a list of messages. An optional ruleName lets callers override its message with a field.ruleName key.

ts
import type { RuleObject } from '@plinthjs/validation'

class Uppercase implements RuleObject {
  readonly ruleName = 'uppercase_rule'

  validate(attribute: string, value: unknown): true | string {
    return typeof value === 'string' && value === value.toUpperCase()
      ? true
      : `The ${attribute} must be uppercase.`
  }
}

Validator.make({ code: 'abc' }, { code: ['required', new Uppercase()] })

Rule Builders ​

The Rule object and its companions build rules fluently. They go in a rules array next to plain strings.

ts
import { Password, Rule } from '@plinthjs/validation'

const rules = {
  role: [Rule.in(['admin', 'user'])],
  status: [Rule.notIn(['banned'])],
  email: ['required', 'email', Rule.unique('users', 'email')],
  password: ['required', Password.min(8).mixedCase().numbers().symbols()],
}

Rule.in(values) and Rule.notIn(values) return the plain in: and not_in: rule strings.

Rule.enum ​

Rule.enum accepts a list of allowed values or an enum-like object (TypeScript enums work too; their reverse numeric mappings are ignored).

ts
const Color = { Red: 'red', Blue: 'blue' } as const

await Validator.make({ c: 'green' }, { c: [Rule.enum(Color)] }).errors()
// => { c: ['The selected c is invalid.'] }

Override the message with the c.enum key.

Password ​

Password builds a password policy. Password.min(n) starts it (the minimum length defaults to 8), and you chain max(n), letters(), mixedCase(), numbers() and symbols(). Every violated requirement produces its own message.

ts
await Validator.make(
  { p: 'abc' },
  { p: ['required', Password.min(8).mixedCase().numbers().symbols()] },
).errors()
// => { p: ['The p must be at least 8 characters.',
//          'The p must contain at least one uppercase and one lowercase letter.',
//          'The p must contain at least one number.',
//          'The p must contain at least one symbol.'] }

Set an application-wide policy once, then reuse it with Password.default():

ts
Password.defaults(() => Password.min(10).numbers())

const rules = { password: ['required', Password.default()] }

Files and Images ​

Rule.file() and Rule.imageFile() expand to file or image plus optional types, min and max (in kilobytes). Rule.dimensions() builds the dimensions rule with width, height, minWidth, maxWidth, minHeight, maxHeight and ratio.

ts
const rules = {
  avatar: [
    'required',
    Rule.imageFile().types(['png', 'jpg']).max(2048),
    Rule.dimensions().minWidth(100).minHeight(100).ratio('1/1'),
  ],
}

Database Rules ​

exists and unique ask a presence verifier to count rows, so the validator never touches a database driver itself. Give the validator an object with a getCount method.

ts
import type { PresenceVerifier } from '@plinthjs/validation'

const verifier: PresenceVerifier = {
  async getCount(table, column, value, excludeId, excludeColumn, extra) {
    // return how many rows in `table` have `column` equal to `value`,
    // ignoring the row whose `excludeColumn` (default 'id') equals `excludeId`,
    // and matching the equality constraints in `extra`
    return countRows(table, column, value, excludeId, excludeColumn, extra)
  },
}

const validator = Validator.make(data, {
  email: ['required', Rule.unique('users', 'email')],
  user_id: ['required', Rule.exists('users', 'id')],
}).setPresenceVerifier(verifier)

When the column is omitted, the field name is used. To let a user keep their own email while editing their profile, ignore their row. Add equality constraints with where:

ts
Rule.unique('users', 'email').ignore(user.id) // ignore by the id column
Rule.unique('users', 'email').ignore(user.uuid, 'uuid') // ignore by another column
Rule.unique('users', 'email').where('tenant_id', 7) // only count rows in one tenant

The string forms exists:users,id and unique:users,email,5,id work the same way. Using either rule without calling setPresenceVerifier throws a clear error. In a form request, call setPresenceVerifier from withValidator (below).

Current Password ​

current_password checks the value against the signed-in user's stored hash. It needs two small seams: a hasher with check(value, hash) and a function returning the current user (an object with a password field).

ts
const errors = await Validator.make({ pw: 'bad' }, { pw: 'current_password' })
  .setHasher({ check: (plain, hash) => plain === hash })
  .setUserResolver(() => ({ password: 'good' }))
  .errors()

errors.all() // => { pw: ['The password is incorrect.'] }

In a real application, pass the hasher from Hashing.

Working With Error Messages ​

validator.errors() returns an ErrorBag:

ts
const errors = await validator.errors()

errors.has('email') // => true
errors.first('email') // the first message for email, or '' when there is none
errors.first() // the first message of the first failing field
errors.get('email') // => all messages for email, [] when none
errors.all() // => { field: string[], ... }
errors.keys() // => the failing field names
errors.count() // => the total number of messages
errors.isEmpty() // / errors.isNotEmpty()
errors.add('email', 'Some extra message.')

The bag has the has and first methods that the @error directive in Views looks for, so you can pass it to a template as errors.

Failing the Whole Run ​

validate() and validated() throw a ValidationError, an Error whose errors property is the same field: messages record and whose status is 422. Its message is The given data was invalid.

ts
import { ValidationError } from '@plinthjs/validation'

try {
  await validator.validate()
} catch (error) {
  if (error instanceof ValidationError) {
    error.status // => 422
    error.errors // => { email: ['The email must be a valid email address.'] }
  }
}

Stopping Early and After Hooks ​

stopOnFirstFailure() stops validating after the first failing field. after(callback) runs once every rule has finished and is the place for checks that span several fields. Add failures through getMessageBag().

ts
const validator = Validator.make({ a: 1 }, { a: 'integer' }).after((v) => {
  v.getMessageBag().add('a', 'Extra problem.')
})

;(await validator.errors()).all() // => { a: ['Extra problem.'] }

Form Requests ​

When validation grows beyond a few lines, move it into a class. Extend FormRequest, define rules(), and optionally messages(), authorize(), prepareForValidation() and withValidator().

ts
import { FormRequest } from '@plinthjs/validation'

import type { MessagesMap, RulesMap, Validator } from '@plinthjs/validation'

export class StorePostRequest extends FormRequest {
  authorize(): boolean {
    return this.request.header('x-admin') === '1'
  }

  rules(): RulesMap {
    return { title: 'required|string|min:3', body: 'required' }
  }

  messages(): MessagesMap {
    return { 'title.required': 'A post needs a title.' }
  }

  protected prepareForValidation(data: Record<string, unknown>): Record<string, unknown> {
    return { ...data, title: String(data['title'] ?? '').trim() }
  }

  protected withValidator(validator: Validator): void {
    validator.setPresenceVerifier(verifier)
  }
}

In a controller, construct it with the request and call validate(), or use the static shortcut:

ts
const data = await new StorePostRequest(request).validate()
// or
const same = await StorePostRequest.validate(request)
// data => { title: 'Hello', body: '...' }

validate() first calls authorize(). If it returns false, an AuthorizationError is thrown, which renders as a 403 response. Otherwise the input is validated and a ValidationError is thrown on failure. The form request also offers validated(), safe(), passes() (true only when authorized and valid, never throws), errors(), all() and input(key, default).

prepareForValidation receives the request input and returns what should be validated, which is where to trim strings or merge in defaults. The validator is built once per form request and reused.

How Failures Are Rendered ​

ValidationError carries a status of 422 and an errors bag, and AuthorizationError carries a status of 403. The HTTP exception handler reads those structurally and builds a response based on what the client wants.

For a request that wants JSON (an Accept: application/json header or an XHR request), the response is a 422 with a JSON body:

json
{
  "message": "The given data was invalid.",
  "status": 422,
  "errors": {
    "email": ["The email must be a valid email address."],
    "name": ["The name field is required."]
  }
}

For a browser request, the handler redirects back to the Referer (or / when there is none), flashing the errors and the old input to the session. Sensitive fields such as passwords are not flashed back. The next request can then show the errors and refill the form. See Session for flashing, Responses for withErrors and withInput, and Error Handling for the handler.

In a view, show a message with the @error directive, and refill fields with the flashed input:

html
<input name="email" value="{{ old('email') }}" />
@error('email')
<p class="error">{{ $message }}</p>
@enderror

An API application can force JSON responses for every request by adding middleware that sets the Accept header to application/json, which is how the generated API stack behaves.

Testing ​

Because the validator needs nothing but data, tests are plain function calls. For a form request, build a Request from a JSON body.

ts
import { Request } from '@plinthjs/http'

const request = new Request({
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ title: 'Hi' }),
})

await expect(new StorePostRequest(request).validate()).rejects.toThrow()

Use Validator.make(...).errors() to assert exact messages, or .passes() for a yes or no.

Released under the MIT License.