4.5.1 • Published 6 months ago

node-input-validator v4.5.1

Weekly downloads
7,689
License
ISC
Repository
github
Last release
6 months ago

Validation Library

NPM version build status Known Vulnerabilities Coverage Status David deps node version

Validation library for node.js

Node Input Validator is a validation library for node.js. You can also extend library to add custom rules.

Installation

npm install --save node-input-validator

Usage

Simple Example

const v = require('node-input-validator');

let validator = new v({name:''}, {name:'required|minLength:5'});

validator.check().then(function (matched) {
    console.log(matched);
    console.log(validator.errors);
});

Example usage in express application

const v = require('node-input-validator');

app.post('login', function (req, res) {

    let validator = new v( req.body, {
        email:'required|email',
        password: 'required'
    });

    validator.check().then(function (matched) {
        if (!matched) {
            res.status(422).send(validator.errors);
        }
    });

})

With async/await

const v = require('node-input-validator');

router.post('login', async function (ctx) {

    let validator = new v( ctx.request.body, {
        email:'required|email',
        password: 'required'
        });

    let matched = await validator.check();

    if (!matched) {
        ctx.status = 422;
        ctx.body = validator.errors;
        return;
    }

})

Objects Validation

    let v = new Validator({
            product: {id:'1',name:'',price:'', active:'yes'}
        },
        {
            'product': 'required|object',
            'product.id': 'required|integer',
            'product.name': 'required',
            'product.price': 'required|integer',
            'product.active': 'required|integer'
        });

    let matched = await v.check();

Array Validation

    let v = new Validator({
            roles: ['admin', 'manager', 'member']
        },
        {
            'roles': 'required|array',
            'roles.*': 'required|string'
        });

    let matched = await v.check();
    let v = new Validator({
            plan: [
                {price:'25',title:'OK'},
                {price:'',title:''},
                {price:'30'},
                {price:'',title:'Title'}
            ]
        },
        {
            'plan': 'required|array',
            'plan.*.price': 'required|integer',
            'plan.*.title': 'required'
        });

    let matched = await v.check();

Extending

Placeholder in messages, :attribute will be replaced with field name, :value with field value and :arg0, :arg1 ...n with arguments passed to rule.

Add/Update rule based messages

Validator.messages({
    required: 'The :attribute field must not be empty.',
    email: 'E-mail must be a valid email address.',
    even: 'The value of the field must be even number.',
    status: 'Invalid status'
});

Add custom messages

//Note: Default language is English (en).

Validator.customMessages({
    'username.required': 'When username attribute required rule failed.',
    username: 'Default message for username attribute.'
});

Add/Update rules default message in another language

Currenlty this package only support english, But you can easliy add messages in another language.

Validator.messages({
    required: ':attribute ਫੀਲਡ ਖਾਲੀ ਨਹੀਂ ਹੋਣਾ ਚਾਹੀਦਾ.',
}, 'pb');

Set default language

const validator = require('node-input-validator');
validator.setLang('pb');

Add your own custom validation rules

Validator.extend('even', async function (field, value) {

    if( (parseInt(value) % 2) == 0 ){
        return true;
    }

    return false;

});

Validator.extend('status', async function (field, value, args) {

    if( args.indexOf(value) >= 0 ){
        return true;
    }

    return false;

});

For Koa2 Attach koa middleware

const validator = require('node-input-validator');
app.use(validator.koa());

Then in controller

let v = await ctx.validate(ctx.request.body, {
        name:'required|maxLength:50', 
        username:'required|maxLength:15',
        email:'required|email',
        password:'required'
    });


let isValid = await v.check();

if (!isValid) {
    // return validation errors
    ctx.body = v.errors;
    ctx.status = 422;

    return;
}

Rules

You can check test cases for rules usage/examples.

required
The field under validation cannot be left blank.

// required rule validation fails
let v = new Validator({name:''}, {name:'required'});

requiredIf:field,value
The field under validation cannot be left blank, if provided seed value equals to provided value seed.

// requiredIf rule validation fails, becoz email cannot be left blank if age is 16
let v = new Validator({email:'', age:'16'}, {email:'requiredIf:age,16'});

requiredNotIf:field,value
The field under validation may left blank, if provided seed value equals to provided value seed.

// requiredNotIf rule validation fails, becoz transport must be present in case age is not 16
let v = new Validator({transport:'', age:'15'}, {transport:'requiredNotIf:age,16'});

requiredWith:field
requiredWith:field,field,field
The field under validation may required in case provided seed present.

// requiredWith rule validation fails, becoz email must in case age present.
let v = new Validator({email:'', age:'17'}, {email:'requiredWith:age'});

requiredWithout:field
requiredWithout:field,field,field
The field under validation may left blank in case provided seed present.

// requiredWithout rule validation fails, becoz email is must in case phone,pan not provided.
let v = new Validator({email:'', username:''}, {email:'requiredWithout:phone,pan', username:'requiredWithout:email'});

accepted
The field under validation must be yes, on, 1, or true.

after:YYYY-MM-DD
The field under validation must be date after provided seed.

let v = new Validator({joining:''}, {joining:'required|after:2018-02-10'});

alpha
The field under validation must be entirely alphabetic characters.

alphaDash
The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alphaNumeric
The field under validation only contains letters and numbers.

array
The field under validation must be an array.

ascii
The field under validation only contains ascii characters.

base64
The field under validation must be valid base64 encoded string.

between:min,max
The field under validation must be betwwen min and max seed. This will work with number valus as well as with arrays using array count.

boolean
boolean:custom The field under validation must be boolean (true, false, 'true', 'false', 0, 1, '0', '1') or in custom seed.

contains:value
The field under validation must contains provided seeds.

let v = new Validator({bio:'My profile is: example.com'}, {bio:'required|contains:profile'});

creditCard
The field under validation must be valid credit card string.

date
The field under validation must be a valid date (YYYY-MM-DD).

dateFormat:format
The field under validation must match the given date format.

let v = new Validator({dob:''}, {dob:'required|dateFormat:YYYY-MM-DD'});

Check https://momentjs.com/docs/ for supported formats

decimal
The field under validation must be a decimal value.

digits:length
The field under validation must be numeric and must have an exact length.

digitsBetween:min,max
The field under validation must have a length between provided min and max values.

let v = new Validator({phone:''}, {age:'required|digitsBetween:10,13'});

domain
The field under validation must a qualified domain.

email
The field under validation must be formatted as an e-mail address.

equals
The field under validation must be equal to given value.

hash:algo
The field under validation must be a valid hash as per provided seed.

 let v = new Validator({ 
        id: 'fd1baf48377a9f644f9af89abbee29f6'
     },
     {
         id: 'required|hash:md5'
     });

Supported algorithms: md4, md5, sha1, sha256, sha384, sha512, ripemd128, ripemd160, tiger128, tiger160, tiger192, crc32, crc32b.

hex
The field under validation must be valid hex.

hexColor
The field under validation must be valid hex color code.

in:a,b...n
The field under validation must exist in the given list of values.

let v = new Validator({status:''}, {status:'required|in:active,inactive,blocked'});

integer
The field under validation must be an integer.

ip
The field under validation must be an IP address.

iso8601
The field under validation must be valid Iso8601 date.

json The field under validation must be a valid JSON string.

latLong The field under validation must be a valid latitude-longitude coordinate.

lengthBetween:min,max
The field under validation value length must be between provided values.

let v = new Validator({age:''}, {age:'required|between:17,30'});

macAddress
The field under validation should be a valid Mac Address.

let v = new Validator({ id: '00:14:22:01:23:45' }, { id: 'required|macAddress' });
;

max
The field under validation must be less than given value.

let v = new Validator({age:''}, {age:'required|max:35'});

maxLength The length of field under validation should be less than given value.

let v = new Validator({username:''}, {username:'required|max:10'});

mime
The file under validation must have a MIME type corresponding to one of the listed extensions.

min The field under validation must be greater than given value.

let v = new Validator({age:''}, {age:'required|min:21'});

minLength
The length of field under validation should be greater than given value.

let v = new Validator({username:''}, {username:'required|max:10|min:5'});

mongoId
The field under validation should be a valid MongoDB ID.

let v = new Validator({id:''}, {id:'required|mongoId'});

notContains:value
The field under validation may not contains provided seeds.

notIn
The field under validation must not exist in the given list of values.

let v = new Validator({status:''}, {status:'required|notIn:inactive,blocked'});

nullable
The field under validation is required only is not left empty.

numeric
The field under validation must be numeric.

phoneNumber
The field under validation must be a valid phone number.

regex
The field under validation must match the given regular expression.

same
The given field must match the field under validation.

let v = new Validator({password:''}, {password:'required|same:confirm_password'});

size:max size:max,min
The file field under validation must have a file size matching the given maximum value or should be between size range. Supported unit sufix: b,kb/k,mb/m,gb/g.

// in below case, image file size should be under 4kb limit
let v = new Validator({image:''}, {image:'required|size:4kb'});
// in below case, image file size should be between 1kb - 4kb
let v = new Validator({image:''}, {image:'required|size:4kb,1kb'});
let v = new Validator({video:''}, {video:'required|size:10mb'});

sometimes
The field under validation is required if present.

string
The field under validation must be string.

url
The field under validation must be a valid URL.

Post Rules There is set of rules which can be used to validate constraints of whole input, rather than validity of singular fields.

const v = require('node-input-validator');

let validator = new v({name:''}, {'*': 'any:name,surname'});

validator.check().then(function (matched) {
    console.log(matched);
    console.log(validator.errors);
});

Post validator errors are returned in the * key. There is also possibility to add custom function as validator with help of addPostRule method. Function will be called in context of validator object with input as parameter.

const v = require('node-input-validator');

let v = new Validator({username: 'arnold', password: 'arnold123'}, {});

v.addPostRule(async function(input) {

    if (input.password.indexOf(input.username) >= 0) {
        this.validator.addError('password', 'custom', 'Password cannot contain username'); 
    }

});

any Any of the fields must be present in input.

all All of the fields must be present in input.

Typescript Support

Typings expermental

5.0.0-beta.8

6 months ago

5.0.0-beta.6

1 year ago

5.0.0-beta.7

1 year ago

4.5.1

1 year ago

4.5.0

2 years ago

5.0.0-beta.5

3 years ago

5.0.0-beta.4

3 years ago

4.4.1

3 years ago

5.0.0-beta.3

3 years ago

4.4.0

3 years ago

4.3.3

3 years ago

4.3.2

3 years ago

4.3.1

3 years ago

5.0.0-beta.2

3 years ago

4.3.0

3 years ago

5.0.0-beta.1

3 years ago

5.0.0-beta.0

3 years ago

5.0.0-rc11

3 years ago

5.0.0-rc10

3 years ago

5.0.0-rc9

4 years ago

5.0.0-rc8

4 years ago

5.0.0-rc7

4 years ago

5.0.0-rc5

4 years ago

5.0.0-rc6

4 years ago

5.0.0-rc4

4 years ago

5.0.0-rc3

4 years ago

5.0.0-rc2

4 years ago

5.0.0-rc1

4 years ago

4.2.2-rc1

4 years ago

4.2.1

4 years ago

4.2.0

4 years ago

4.2.0-rc2

4 years ago

4.2.0-rc1

4 years ago

4.1.0

5 years ago

4.1.0-rc1

5 years ago

3.8.0

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

4.0.0-rc6

5 years ago

4.0.0-rc5

5 years ago

3.7.3

5 years ago

4.0.0-rc4

5 years ago

4.0.0-rc3

5 years ago

4.0.0-rc2

5 years ago

4.0.0-rc1

5 years ago

3.7.2

5 years ago

3.7.1

5 years ago

3.7.0

5 years ago

3.7.0-rc2

5 years ago

3.7.0-rc1

5 years ago

3.6.4

5 years ago

3.6.3

5 years ago

3.6.2

5 years ago

3.6.1

5 years ago

3.6.0

5 years ago

3.6.0-rc2

5 years ago

3.6.0-rc1

5 years ago

3.5.0

5 years ago

3.4.2

5 years ago

3.4.1

5 years ago

3.4.0

5 years ago

3.4.0-rc1

5 years ago

3.3.0

5 years ago

3.3.0-rc3

5 years ago

3.3.0-rc2

5 years ago

3.3.0-rc1

5 years ago

3.2.0

5 years ago

3.2.0-rc3

5 years ago

3.2.0-rc2

5 years ago

3.2.0-rc1

5 years ago

3.1.0

5 years ago

3.1.0-rc3

5 years ago

3.1.0-rc2

5 years ago

3.0.0-rc1

5 years ago

2.3.4

5 years ago

2.3.3

5 years ago

2.3.2

6 years ago

2.3.1

6 years ago

2.3.0

6 years ago

2.2.0

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.3

6 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.0.9

7 years ago

1.0.8

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago