Forg.js is a Lightweight JavaScript Object Validator


December 11th, 2018

Forg.js is a Lightweight JavaScript Object Validator

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:

const { Validator, Rule } = require('@cesium133/forgjs');
const emailRule = new Rule({
type: 'email',
user: user => user === 'dedede',
domain: domain => ['outlook', 'gmail', 'yahoo'].indexOf(domain) !== -1,
}, null);
const passwordRule = new Rule({
type: 'password',
minLength: 8,
uppercase: 1,
numbers: 1,
matchesOneOf: ['@', '_', '-', '.', '!'],
}, null);
const vComplexe = new Validator({
age: new Rule({ type: 'int', min: 18, max: 99 }),
dateOfBirth: new Rule({ type: 'date' }),
array: new Rule({ type: 'array', of: new Rule({ type: 'string' }) }),
email: emailRule
pasword: passwordRule
age: 26,
dateOfBirth: new Date(1995, 10, 3),
array: ['1'],
email: ';',
password: 'ad1_A@@Axs',
}); /// returns true

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

age: 16,
dateOfBirth: 123,
}); // ['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:

npm install @cesium133/forgjs

Filed in:

Paul Redmond

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