News

Forg.js is a Lightweight JavaScript Object Validator

Published
Forg.js is a Lightweight JavaScript Object Validator image

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

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article