favalid
Validator Framework for javascript.
Getting Started
Prerequisites
- Node.js v8+
- npm or yarn
Installing
$ npm install favalid
Usage
Primitive Validator
- Write higher order validator using
tester()
.tester()
takes two arguments. first argument is(value: any) => bool
function, which represent validation rules. Second argument is() => string
function, which represents validation error message.
; const validator =
- Use it!
tester()
returns simple validator function,(value: any) => ({error: bool, message: string})
.
console; // => { error: false, message: '' }console; // => { error: true, message: 'must ne less than 100' }
Combined Validator
- You can combine these validators using
combine(...validators)
.combine()
returns also validator.
;const validator1 = const validator2 = const combinedValidator =
- Use it.
console // { error: false, message: '' } console // { error: true, message: 'must be less than 100' } console // { error: true, message: 'must be higher than 20' }
If target values are failed multiple tests, combined validator returns first failed message.
;const minLength = const regex = const combinedValidator = console // { error: true, message: 'too few letters' } console // { error: true, message: 'too few letters' } console // { error: true, message: 'invalid format' }
Using Predefined Higher Order Validators
You can also use predefined higher order validators found on favalid/lib/validators
.
These validators can be combined with your original validators.
; const combinedValidator =
Validation Result Reducers
You can aggregate validate errors with your customize error reducer using conbineWithReducer(validators, reducer, initialValue)
.
; const REQUIRED_EMAIL_MESSAGE = "required."; const EMAIL_REGEXP = /^@$/i;const REGEXP_MESSAGE = "invalid email."; const EMAIL_MAX_LENGTH = 100;const MAX_LENGTH_MESSAGE = "exceeds 100 letters."; const EMAIL_MIN_LENGTH = 10;const MIN_LENGTH_MESSAGE = "at least 10 letters."; const emailValidatorWithMultipleErrorReducer = { const reducer = { if currentErrorerror prevError; return prevError; }; return email;}; console // => []console // => [{error: true, message: 'at least 10 letters.'}, {error: true, message: 'invalid email.'}]
Examples
See src/examples.
License
This project is licensed under the Apache License 2.0 License - see the LICENSE file for details