Secure data validation in JS
npm i verif
const {Validator, Range} = require('verif')
const myValidator = new Validator({
'type': 'object',
'props': {
'name': {
'type': 'string',
'length': Range(3, 23)
},
'age': {
'type': 'number',
'value': Range(5, 4000)
}
}
})
myValidator.test({
'name': 'Tester',
'age': 17
})
// This will not throw; data is acceptable.
myValidator.test({
'name': 'Tester',
'age': 4
})
// This will throw an error:
// Error: Number value 4 out of bounds. Expected in [5, 4000]
const res = myValidator.validate({
'name': 'Tester',
'age': 4
})
// This will return information about the validation:
/*
{
passed: false,
message: 'Number value 4 out of bounds. Expected in [5, 4000]',
path: '/age/'
}
*/
// new Range(min: number, max: number, inclusive: boolean)
new Range(4, 7, false)
// Exclusive range (4, 7)
new Range(6, 10, true)
new Range (6, 10)
// Inclusive range [6, 10]
For all validations, a type
must be specified.
-
Range
valuePermitted number value range
-
Range
lengthPermitted string length range
-
RegEx
testMandatory string regular expression test
-
Range
lengthPermitted array length range
-
schema
itemsSchema for item testing
-
Object[schema]
propsSchemas for testing individual properties
-
boolean
allowExtraPropsPermit the inclusion of additional properties not defined in
props
Default:
false