Request validator
This package is useful for validating request bodies.
NOTE: All fields are reqired by default.
Existsing rules:
Optional property:
Put ? at the end of property name.
'property?' : 'string'Integer:
'property' : 'integer'Number: (any kind of number)
'property' : 'number'String:
'property' : 'string'Array:
'property' : 'array'Object:
'property' : 'object'Email:
'property' : 'email'Length:
'property' : 'length:(max|min),(int)''property' : 'length:max:50',Size:
'property' : 'length:(max|min),(int)'Range (inclusive):
'property' : 'range:(min),(max)''property' : 'range:5,10'Boolean:
It has a strict mode and non strict mode.
In strict mode it just accepts true and false.
In non strict mode it accepts 'true', 'false', 1, 0, '1' and '0'.
'property' : 'boolean:(strict)''property' : 'boolean' // strict mode'property' : 'boolean:true' // non strict modeCustom validator:
It should return the result of validation and error message.
Error message is used if result is false.
'property': [() =>{
return {
result: true,
message: "return error message"
}
}]Using multiple validation rules:
Seprate them by | :
'property': 'number|range:4,8'Pass rules as array:
'property': ['number', 'range:4,8']Validate object's properties:
'property.child': 'number',Validate array indexes:
Every index should be a number:
'property.*': 'number'Every index is a object which has a name and an age:
'property': 'array':
'property.*.name': 'string|length:max,50',
'property.*.age': 'number|range:18,150',Example
const validate = require('@alxgh/validate');
const {errors, output, failed} = validate({
'username': 'string|length:min,4|length:max,50',
'password': 'string|length:min,6',
'last_name': 'string|length:max,50',
'first_name': 'string|length:max,50',
'role?': 'integer',
}, input);
if(failed) {
// Validaton has failed
// use the `errors`
} else {
// Use the `output`. it does not contain extra fields.
}In above example the object should have username, password, last_name, first_name and role which is optional.