Skip to content

@plinthjs/validation ​

A rule-based validator with error bags - the Plinth take on the conventional validation API.

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

const validator = Validator.make(
  { name: 'Ada', email: 'ada@example.com', password: 'secret', password_confirmation: 'secret' },
  {
    name: 'required|string|min:3',
    email: 'required|email',
    password: 'required|confirmed|min:6',
    'profile.age': 'sometimes|integer|between:18,120',
  },
)

if (validator.passes()) {
  const clean = validator.validated() // only the validated fields
}

Rules ​

required, nullable, string, integer, numeric, boolean, email, url, min, max, between, in, notIn, regex, confirmed, same:other, different:other, array, sometimes.

  • nullable lets a null/undefined/'' value skip every other rule on the field.
  • sometimes skips the field entirely when its key is absent from the data.
  • confirmed checks that <field> equals <field>_confirmation.
  • same/different compare against another (dot-path) field.

Rules may also be supplied as arrays, including parameterised tuples and closures:

ts
Validator.make(data, {
  age: ['required', ['between', 18, 120]],
  slug: ['required', (value) => (/^[a-z-]+$/.test(String(value)) ? true : 'Bad slug.')],
})

API ​

  • Validator.make(data, rules, messages?)
  • passes(), fails(), validate(), validated(), errors()
  • ErrorBag: has(field), first(field?), get(field), all(), isEmpty(), add(field, msg)
  • ValidationError extends Error with .errors: Record<string, string[]>

Custom messages are keyed by 'field.rule' (most specific) or bare 'rule', and support the :attribute, :other, :min, :max, :values placeholders.

Released under the MIT License.