Many API's and application use express-validator as a validator for their HTTP request data. I have been working lately a lot with laravel and when it comes to data validation express-validator can't compete with the built-in validator that come with Laravel especially when you know all the rules.
Bevor it's a Laravel alike validator to validate incoming data, it was built in the same way, for now not all the rules are defined but it comes with some of the most util one.
This module is still in beta use it at your own risk, if you find an anomaly or an issue you can create a new Issue or open a new Pull Request.
npm install bevor --save
Bevor cam with a Validator
instance that accept a payload object, an array of rules to define on each field and options.
Basic usage:
const { Validator } = require('bevor');
const validator = new Validator(
payload, // payload is an object of data.
rules, // rules is an array of rule.
);
Options are set-to debug, return the first occurred error, or to set default error message. Example:
const { Validator } = require('bevor');
const validator = new Validator(payload, [
{ required: 'required' },
{ json: 'json' },
], {
debug: true,
first_error: true,
validation_messages: {
required: 'Ce champ "{{ field }}" est requis.'
}
});
// code
});
The best way to use validation_messages
option is for multi language API or just to change the default messages.
const { Validator } = require('bevor');
let payload = {
username: 'johndoe',
email: 'johndoe@gmail.com',
password: 'secret',
birthdate: '1970-01-01T20:42:35.827Z',
type: 'particular',
setting: { notification: { email: false } },
}
const validator = new Validator(payload, [
{ username: [
'required',
'string',
{
'custom': (value, field, payload) => {
return value == 'johndoe';
}
},
] },
{ email: ['required', 'email'] },
{ password: ['required', 'string', 'min:6', 'max:32'] },
{ birthdate: ['required', 'date'] },
{ type: ['required', 'in:particular,professional'] },
{ age: ['nullable', 'integer', 'gte:20', 'lt:40'] },
{ "setting.notification.email": ['boolean'] },
], {
debug: false,
validation_messages: {
'required': 'You need to make sure that this: "{{ field }}" is defined',
}
});
console.log(
'[!]',
'Is valid:', validator.validate(),
'errors:', validator.errors(),
);
const { Validator } = require('bevor');
// code
//...
app.post('/articles', (req, res, next) => {
const validator = new Validator(req, [
{ 'req.body.name': 'required|string' },
{ 'req.body.price': 'required|numeric|min:100|max:999' },
{ 'req.body.quantity': ['required', 'integer', 'max:10', 'gte:1'] },
{ 'req.file': ['nullable', 'image'] }, // experimental
]);
if (validator.validate() == false)
return res.status(400).send({ state: false, errors: validator.errors() });
let article = req.body;
});
List of all available validation rules:
- array
- bail
- between
- boolean
- custom
- date
- eq
- exists
- gt
- gte
- image experimental
- in
- integer
- ip
- ipv6
- json
- lt
- lte
- max
- min
- not_eq
- not_in
- nullable
- numeric
- regex
- required
- required_if
- size
- string
- timestamp
- url
The field being validated must be a valid array.
Stop running validation rules after the first failure under the current field.
The field being validated has a maximum and minimum value of the set value. Example: between:10,2
the 10
is the maximum value and 2
is the minimum value to which the field must be equal.
The field being validated must be a valid boolean, it can be 1
, 0
, true
or false
.
Custom is used to specify a new rule, it takes a function that returns a boolean. Example:
const validator = new Validator(payload, [
{ field: [
{
'custom': (value, field, payload) => {
return value.charAt(0) === 'A';
}
},
] },
]);
The field being validated must be a valid date string supported by ISO 8601 Date.
The field being validated must be a valid email address.
The field being validated is equal than to the set value. Example: same as gte.
The field being validated must exist(must be true).
The field being validated is greater than to the set value. Example: same as gte.
The field being validated is greater than equal to the set value. Example: gte:2
that mean the field is greater than equal 2
.
The field beign validated must be an image (jpg, jpeg, png, or gif).
The field being validated is included in the list defined in the options separated by ,
. Example: in:cat,dog,frog
.
don't use spaces between coma.
The field being validated must be an integer.
The field being validated must be a ipv4 address.
The field being validated must be a ipv6 address.
The field being validated must be a valid json.
The field being validated is less than to the set value. Example: same as gte.
The field being validated is less than to the set value. Example: same as gte.
The field being validated has a maximum value of the set value. Example: max:10
the 10
is the maximum value to which the field must be equal.
The field being validated has a minimum value of the set value. Example: min:2
the 2
is the minimum value to which the field must be equal.
The field being validated is not equal than to the set value. Example: same as gte.
The field being validated is not included in the list defined in the options separated by ,
. Example: not_in:cat,dog,frog
.
The field under validation can have the value null
, unless required
is provided the rule nullable
will be neglected.
The field being validated must be a numeric (float or integer).
The field being validated match the regex of the set value. Example: regex:/([A-Z])\\w+/gi
this regex match every word not containing numerique values.
you need to escape
\
with\\
.
The field under validation is considered as required
if it's not equal to undefined, empty string, empty array and an empty object.
The field being validated is considered required
if another field is equal to a specific value. Example: required_if:role,admin
here the field beign validated is require only when the field role
is equal to admin
.
The field being validated must have the length of set value, Example: size:255
the field length should equal to 255
.
The field being validated must be a string.
The field being validated must be a valid timestamp.
The field being validated must be a valid url.
made with ❤️ by @hihebark