Forg.js is a Lightweight JavaScript Object Validator

News

December 11th, 2018

forg.js.png

Forg is a lightweight JavaScript object validator by @oussamahamdaoui that simplifies complex validation rules on the frontend. Here are some examples from the project’s readme:

1const { Validator, Rule } = require('@cesium133/forgjs');
2
3const emailRule = new Rule({
4 type: 'email',
5 user: user => user === 'dedede',
6 domain: domain => ['outlook', 'gmail', 'yahoo'].indexOf(domain) !== -1,
7}, null);
8
9const passwordRule = new Rule({
10 type: 'password',
11 minLength: 8,
12 uppercase: 1,
13 numbers: 1,
14 matchesOneOf: ['@', '_', '-', '.', '!'],
15}, null);
16
17const vComplexe = new Validator({
18 age: new Rule({ type: 'int', min: 18, max: 99 }),
19 dateOfBirth: new Rule({ type: 'date' }),
20 array: new Rule({ type: 'array', of: new Rule({ type: 'string' }) }),
21 email: emailRule
22 pasword: passwordRule
23});
24
25vComplexe.test({
26 age: 26,
27 dateOfBirth: new Date(1995, 10, 3),
28 array: ['1'],
29 email: 'my-email@yahoo.fr;',
30 password: 'ad1_A@@Axs',
31}); /// returns true

Once you have a validator instance, you can get the errors from the validator:

1vComplexe.getErrors({
2 age: 16,
3 dateOfBirth: 123,
4 }); // ['age must be integer and between 18 and 99', 'date must be a date']

I am using this library on the frontend for form validation in SPA applications using Vue. You can make some pretty neat validation rules with this package, like the password rule type (see the first example above).

You can use this package to validate any object, and in my case, using data that are bound to a Vue component to give back error messages on the frontend easily.

You can check out the source code at oussamahamdaoui/forgJs on GitHub and install the NPM package with:

1npm install @cesium133/forgjs

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.