bevor

Validate payload

Usage no npm install needed!

<script type="module">
  import bevor from 'https://cdn.skypack.dev/bevor';
</script>

README

halmet - source: https://openclipart.org/detail/294739/helmet-10

Bevor

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.

Instalation

npm install bevor --save

Usage

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.

Examples

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'] },
  { 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;

});

API documentation

List of all available validation rules:

array

The field being validated must be a valid array.

bail

Stop running validation rules after the first failure under the current field.

between

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.

boolean

The field being validated must be a valid boolean, it can be 1, 0, true or false.

date

The field being validated must be a valid date string supported by ISO 8601 Date.

email

The field being validated must be a valid email address.

eq

The field being validated is equal than to the set value. Example: same as gte.

exists

The field being validated must exist(must be true).

gt

The field being validated is greater than to the set value. Example: same as gte.

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.

image

The field beign validated must be an image (jpg, jpeg, png, or gif).

in

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.

integer

The field being validated must be an integer.

ip

The field being validated must be a ipv4 address.

ipv6

The field being validated must be a ipv6 address.

json

The field being validated must be a valid json.

lt

The field being validated is less than to the set value. Example: same as gte.

lte

The field being validated is less than to the set value. Example: same as gte.

max

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.

min

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.

not_eq

The field being validated is not equal than to the set value. Example: same as gte.

not_in

The field being validated is not included in the list defined in the options separated by ,. Example: not_in:cat,dog,frog.

nullable

The field under validation can have the value null, unless required is provided the rule nullable will be neglected.

numeric

The field being validated must be a numeric (float or integer).

regex

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 \\.

required

The field under validation is considered as required if it's not equal to undefined, empty string, empty array and an empty object.

required_if

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.

size

The field being validated must have the length of set value, Example: size:255 the field length should equal to 255.

string

The field being validated must be a string.

timestamp

The field being validated must be a valid timestamp.

url

The field being validated must be a valid url.


made with :heart: by @hihebark