Validators

Learn how to create custom validators.

๐Ÿ™‚ Do not hesitate to create PRs with your custom validators!

Anatomy of a validator

Definition / Rules

  • A validator consist of a Function returning another Function (validator-child), itself returning a boolean.
  • Any validator-child should return true if the condition is met, and false if not.
  • ๐Ÿšจ A validator should never crash, but rather return false if an invalid input is given.
๐Ÿค“ Best practice is to store one validator per file, and export it by default (export default).

Notes

  • In the example below, we used type helpers from vuito/lib/types.
  • VLengthy is here to represent a value that might have a length property, it is not required, and only useful in this case as we are using the length property.

Example

More examples in the validators directory of vuito core.

maxLength.ts
import type { VLengthy, VRow } from 'vuito/lib/types';

export default function (max: number): VRow['test'] {
  return (value: VLengthy) => !value || value.length <= max;
}
Testing
import maxLength from './maxLength';

const v = maxLength(8)
// `v` is now a function like this: `(value) => !value || value.length <= 8`

console.log(v('123')) // true, as "123" length is smaller than 8
console.log(v('12345678')) // false, as "12345678" length is equal 8
console.log(v('123456789')) // false, as "123456789" length is bigger than 8

// Always make sure to handle any "stupid" input, as this is the goal of a validation library.
// Your validator should never crash, but rather return false if an invalid input is given.

console.log(v(null)) // false
console.log(v(99)) // false