0.1.2 • Published 3 years ago

@petitviolet/ts-validator v0.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

ts-validator

Installation

$ npm i @petitviolet/ts-validator

Usage

type Param = {
  name: string
  email: string
  age: number
}

const result = validate(
  {
    name: 'bob',
    email: 'bob@example.com',
    age: 120,
  },
  {
    name: [
      [name => name.length > 0, 'must not be empty'],
      [name => sleep(1).then(() => !['bob', 'charlie'].includes(name)), 'must be unique'],
    ],
    email: [
      [email => /^.+@.+$/i.test(email), 'must be in email format'],
      [email => sleep(1).then(() => !['bob@example.com', 'charlie@example.com'].includes(email)), 'is already taken'],
    ],
    age: [
      [age => age > 0 && age < 120, 'must be between 0 and 120'],
    ],
  }
)
console.dir(result)
// {
//   valid: false,
//   errors: {
//     name: ['must be unique'],
//     email: ['is already taken'],
//     age: ['must be between 0 and 120'],
//   },
// }

See tests files for more examples.

LISENCE

MIT