validator-chain-util is a utility library for the validator.js project. You can verify data through chain functions, or use schema to verify data. It supports wildcard attribute selectors, you can use wildcards to validate data inside arrays or objects.
# NPM
npm install validator-chain-util
# Yarn
yarn add validator-chain-util
const { valid,validatorCheck} = require('validator-chain-util'); // only chain
const { valid,validatorSchema,validatorCheck } = require('validator-chain-util'); // chain and schema
import valid,{validatorCheck} from 'validator-chain-util'; // only chain
import valid,{validatorSchema,validatorCheck} from 'validator-chain-util'; // chain and schema
const testObj = {
name: 'test',
age: 18,
email: '[email protected]',
files: [
{
name: 'test1',
size: 100,
},
{
name: 'test2',
size: 200,
},
],
}
const emailCheck = valid("email").isEmail().run(testObj)
// {pass: true, msg: '',data:[]}
const nameCheck = valid("name")
.notEmpty()
.isLength({ min: 5 })
.withMessage("name is too short")
.run(testObj)
// {
// pass: false,
// msg: 'name is too short',
// data: [ { pass: false, fun: '_isLength', msg: 'name is too short' } ]
// }
console.log(valid("age").isInt().run(testObj))
// {pass: true, msg: '',data:[]}
/* Optional field check */
console.log(valid("phone")
.optional() // If the field is not present, skip the check
.isMobilePhone("en-US")
.run(testObj))
// {pass: true, msg: '',data:[]}
/* Check the data in the array */
console.log(
valid("files.1.name")
.notEmpty()
.isLength({ min: 5 })
.withMessage("name is too short")
.run(testObj))
// { pass: true, msg: '', data: [] }
/* If you just want to check a data */
console.log(valid().isEmail().run("[email protected]"))
// { pass: true, msg: '', data: [] }
/* use validatorCheck */
validatorCheck(emailCheck) // true
validatorCheck(nameCheck) // false
validatorCheck([emailCheck, nameCheck]) // false
const schema = {
name: valid().notEmpty().isLength({ min: 5 }),
age: valid().isInt(),
email: valid().isEmail(),
files: valid().isArray()
}
const checkResult = validatorSchemaCheck(schema, testObj)
// [
// { pass: false, msg: '_isLength', data: [ [Object] ] },
// { pass: true, msg: '', data: [] },
// { pass: true, msg: '', data: [] },
// { pass: true, msg: '', data: [] }
// ]
/* use validatorCheck */
validatorCheck(checkResult) // false
valid("files.*.name")
.notEmpty()
.isLength({ min: 5 })
.withMessage("name is too short")
.run(testObj)
// { pass: true, msg: '', data: [] }
valid("files.*")
.isObject()
.run(testObj)
// { pass: true, msg: '', data: [] }
valid("a.*.*").isInt().run({ a: { b: { c: 1 } } })
// { pass: true, msg: '', data: [] }
/* schema */
const schema = {
files: valid().isArray(),
"files.*.name": valid().notEmpty().isLength({ min: 5 }),
"files.*.size": valid().isInt(),
}
validatorSchemaCheck(schema, testObj)
// [
// { pass: true, msg: '', data: [] },
// { pass: true, msg: '', data: [] },
// { pass: true, msg: '', data: [] }
// ]
validatorCheck(validatorSchemaCheck(schema, testObj)) // true
bail()
will stop checking if the current check fails
valid("name")
.isLength({ min: 6 })
.withMessage("name length must > 6")
.isLength({ min: 5 })
.withMessage("name length must > 5")
.run(testObj)
// {
// pass: false,
// msg: 'name length must > 6',
// data: [
// { pass: false, fun: '_isLength', msg: 'name length must > 6' }
// { pass: false, fun: '_isLength', msg: 'name length must > 5' }
// ]
// }
valid("name")
.isLength({ min: 6 })
.withMessage("name length must > 6")
.bail() // If the current check fails, stop checking
.isLength({ min: 5 })
.withMessage("name length must > 5")
.run(testObj)
// {
// pass: false,
// msg: 'name length must > 6',
// data: [{ pass: false, fun: '_isLength', msg: 'name length must > 6' }]
// }
optional()
and allowNull()
are different, optional()
will skip the check if the field is not present, allowNull()
will skip check the field if the field is present, but the value is null.
notEmpty()
will check the field is "".
optional() | allowNull() | notEmpty() | input value |
---|---|---|---|
false | false | false | ❌undefined must value error, stop checking ❌ null must value error, stop checking "" check next function normal value check next function |
true | false | false | ✅undefined skip all check ❌ null must value error, stop checking "" check next function normal value check next function |
false | true | false | ❌undefined must value error, stop checking ✅ null skip all check "" check next function normal value check next function |
false | false | true | ❌undefined must value error, stop checking ❌ null must value error, stop checking ❌ "" _notEmpty error, then check next normal value check next function |
true | true | false | ✅undefined skip all check ✅ null skip all check "" check next function normal value check next function |
false | true | true | ❌undefined must value error, stop checking ✅ null skip all check ❌ "" _notEmpty error, then check next normal value check next function |
true | false | true | ✅undefined skip all check ❌ null must value error, stop checking ❌ "" _notEmpty error, then check next normal value check next function |
true | true | true | ✅undefined skip all check ✅ null skip all check ❌ "" _notEmpty error, then check next normal value check next function |
valid("email").isEmail().run({})
// {
// pass: false,
// msg: 'must value',
// data: [ { pass: false, fun: '', msg: 'must value' } ]
// }
/* Optional Filed */
// If the field is not present, skip the check
// If the field is null,cannot skip the check
valid("email").optional().isEmail().run({})
// { pass: true, msg: '', data: [] }
valid("email").optional().isEmail().run({email:null})
// {
// pass: false,
// msg: 'must value',
// data: [ { pass: false, fun: '', msg: 'must value' } ]
// }
/* Allow Null */
// If the field is not present, cannot skip the check
// If the field is null, skip the check
valid("email").allowNull().isEmail().run({})
// {
// pass: false,
// msg: 'must value',
// data: [ { pass: false, fun: '', msg: 'must value' } ]
// }
valid("email").allowNull().isEmail().run({email:null})
// { pass: true, msg: '', data: [] }
/* notEmpty */
// If the field is empty (is ""), the check will fail
valid("email").notEmpty().isEmail().run({email:""})
// {
// pass: false,
// msg: '_notEmpty',
// data: [ { pass: false, fun: '_notEmpty', msg: '_notEmpty' } ]
// }
valid().customer((value:string,rawValue:any):boolean=>{
if(value === 'test'){
return true
}
return false
}).run(testObj)
// value is the input value to string
// rawValue is the input value to raw type
valid("name")
.isLength({min:5})
.withMessage('name is too short')
.contains('test')
.withMessage('name must contains test')
.run(testObj)
Validation chains or schemas is a object,they are mutable.
This means that calling methods on one will cause the original chain object to be updated.
If you want to reuse a chain or schema, you can return it from a function.
//use chain
const chain=()=>valid("name").isLength({min:5})
chain().run(testObj)
//use schema
const schema=()=>{
return{
name:valid().isLength({min:5}),
age:valid().isInt({min:18})
}
}
validatorSchemaCheck(schema(),testObj)
Warning
Storing chains or schema and then calling methods on them might cause bugs.
This example will give wrong results on the second call.const chain=valid("name").isLength({min:5}).bail() chain.run({name:"test"}) // pass is false chain.run({name:"test1"}) // Should be true, but was false
View Change Log