Socket
Socket
Sign inDemoInstall

js-simple-validator

Package Overview
Dependencies
3
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    js-simple-validator

Convenient data validator


Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

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

Keywords

FAQs

Last updated on 08 Dec 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc