Skip to content

OxCom/constraint-validator

Repository files navigation

Constraints form validator

npm version Build Status codecov

This library contains list of classes that allows developers to create custom validation flows.

The main idea to have configured form with rules for each field. Each field can be validated by specific constraint.

Validation constraints inspired by Symfony Constraints.

Install

npm i constraint-validator --save

Basic usage

CommonJS module
var validator = require("constraint-validator");
var form = new validator.Form();

form
    .add('email', [
        new validator.NotBlank(),
        new validator.Email(),
    ])
    .add('password', [
        new validator.NotBlank(),
        new validator.Length({min: 6}),
    ]);
    
var errors = form.validate({
    email: 'email@example.com',
    password: '123456',
});
ESM module
import { Form, NotBlank, Email, Length } from 'constraint-validator';

const form = new Form();

form
    .add('email', [
        new NotBlank(),
        new Email(),
    ])
    .add('password', [
        new NotBlank(),
        new Length({min: 6}),
    ]);

const errors = form.validate({
    email: 'email@example.com',
    password: '1234567',
});
Error handing

In case of form data is not valid the errors object contains properties (related to from filed names) and array of Error objects.

{
    'email': [
        Error,
        Error,
    ],
    'password': [
        Error,
    ]   
}

Otherwise error variable will be empty object {}

Data transformers

Data transformers are used to translate the data for a field into a other format and back. The data transformers act as middleware and will be executed in the same order as they were applied.

There are 2 types of data transformers:

  • transformer - executes before validation process
  • reverseTransformers - executes after validation process

Form data transformers

import { Form, NotBlank, Email } from 'constraint-validator';

const form = new Form();

form
    .add('email', [
        new NotBlank(),
        new Email(),
    ])
    // next transformers will be applied to the form data
    .addTransformer(data => {
        data.email += '@example.com'

        return data;
    })
    .addReverseTransformer(data => {
        data.email = data.email.replace(/@example.com/, '@example.me');
        
        return data; 
    });

form.validate({email: 'email'});

console.log(form.getData());
// Output:
// {"email": "email@example.me"}

Field data transformers

import { Form, NotBlank, Email } from 'constraint-validator';

const form = new Form();

form
    .add('email', [
        new NotBlank(),
        new Email(),
    ])
    .get('email')
    // next transformers will be applied to the 'email' field only
    .addTransformer(value => value + '@example.com')
    .addReverseTransformer(value => value.replace(/@example.com/, '@example.me'));

form.validate({email: 'email'});

console.log(form.getData());
// Output:
// {"email": "email@example.me"}

Documentation

You can create custom constrains by using deep integration.

Dependencies

  • locutus - JavaScript implementation of PHP functions
  • Luxon Moment - DateTime manipulation library
  • IpAddrJs - IP address manipulation library

Notes

Q: Why not exceptions?
A: See try/catch performance test

Q: Is there same logic as symfony has?
A: No, please check documentation for each constraint

TODO

  • Provide types.d.ts for better user experience
  • CI/CD build flow (drop dist folder)
  • Proper package integration (get IDE autocomplete working better)
  • Investigate DayJS as replacements: find a way to validate timezones.