Forg.js is a Lightweight JavaScript Object Validator

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
});

vComplexe.test({
  age: 26,
  dateOfBirth: new Date(1995, 10, 3),
  array: ['1'],
  email: 'my-email@yahoo.fr;',
  password: 'ad1_A@@Axs',
}); /// returns true

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

vComplexe.getErrors({
    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: News / frontend / javascript / Validation


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Full-Stack Developer (PHP+JS)
Remote
The Interaction Design Foundation
Senior Laravel Developer
Remote
Sonar
Laravel / Vue.JS Developer - Join an amazing team!
Remote
JTR Solutions
Mid / Sen. Software Engineer
Clearwater, FL
ShineOn
Remote PHP / Laravel Developer
Remote
SpringboardVR
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Laravel Developer
Leidseplein, Amsterdam
Orderchamp.com