js-simple-validator
TypeScript icon, indicating that this package has built-in type declarations

1.1.7 • Public • Published

Convenient data validation library!

Validate data with the comfort of your soul!

npm i js-simple-validator

Examples

Basic usage

import {Validator} from 'js-simple-validator';
try{
	
    let data = {
        id : 1,
        name : 'Tomato',
        price : 25.22
    }
	
    let {id, name, price, comment} = Validator.make(
        {
            id      : Validator.rule.setRequired().isInt(),
            name    : Validator.rule.setRequired().isString().trim().length(1, 255),
            price   : Validator.rule.setRequired().isNumeric().after(0).max(10000),
            comment : Validator.rule.setDefault(null).isString().length(1, 4096)
        }
    ).validate(data);
	
    console.log(id);      //Number(1)
    console.log(name);    //String('Tomato')
    console.log(price);   //Number(25.22)
    console.log(comment); //Null
	
}catch(ValidatorError e){
    console.log(e);
}

Simple validation

try{

    let validator = Validator.rule
        .isString()
        .regex(/^[A-z]+$/);
	
	let result = validator.validate('Value');
	
}catch (ValidatorFieldError e){
    console.log(e);
}

No errors mode

In case of an error, no exception will be thrown. Instead - the field will get a default value (or null).

For all fields in Validator:

Validator.make(...).errNo().validate(...);

For current rule:

Validator.rule.isString().errNo();

Validator methods

Validator.errNo()
Validator.setCustomErrors(errors)
Validator.validate(data)

Validator.rule methods

.custom(fn)
.assert(fn [, message])
.try(message, fn)
.errNo()
.setDefault(val)
.setRequired()
.setCustomErrors(errors)
.validate(data)

Default validate methods

.isString()
.isNumeric()
.isInt()
.isBoolean()
.length(min, max)
.range(min, max)
.min(min)
.max(max)
.in(values)
.notIn(values)
.regex(regularExpression)
.regexSearch(regularExpression)
.after(min)
.before(max)
.isCreditCard()
.isDate(format = 'YYYY-MM-DD')
.isEmail()
.isJSON(parse = true)
.isLowerCase()
.isUpperCase()
.isArray()
.isObject()
.inObjectKeys(obj)
.trim()
.isJSON(parse = false)
.stripTags()
.encodeHtmlChars()
.urlDecode()

Custom validation

assert(fn [,errorMessage])

The function must return true or false.

Validator.rule
    .isString()
    .assert(item => item.length > 5)
    .stripTags();

custom(fn)

The function must throw an error or return a new value. Any type. You can throw only ValidatorFieldError from the custom callback.

Validator.rule.isString().custom(item => {

    if (item.length > 5) {
        throw new ValidatorFieldError('Bad length');
    }

    return item.substr(0, 2);

});

try(errorMessage, fn)

Everything that happens inside this function will cause a specific error:

Validator.rule.isString().try('Specific error message', field => {
	
    field.custom(item => item.split("|"))
         .assert(item => item.length > 5);
    
});

Custom error messages

To change default error messages - use setCustomErrors

import {errors} from 'js-simple-validator';

console.log(errors.DefaultErrors);

let myErrorMessages = {
    'isString' : 'String is bad',
    'trim' : 'Trim error'
}
Validator.make({...}).setCustomErrors(myErrorMessages)
Validator.rule.isString().setCustomErrors(myErrorMessages);

Package Sidebar

Install

npm i js-simple-validator

Weekly Downloads

1

Version

1.1.7

License

ISC

Unpacked Size

30.1 kB

Total Files

30

Last publish

Collaborators

  • in4in