Recommend this page to a friend! |
Download |
Info | Documentation | Files | Download | Reputation | Support forum | Blog | Links |
Last Updated | Ratings | Unique User Downloads | Download Rankings | |||||
2023-10-28 (9 months ago) | Not yet rated by the users | Total: 40 | All time: 513 This week: 4 |
Version | License | JavaScript version | Categories | |||
node-input-validator 1.0 | Freeware | 5 | Validation, Node.js, Forms, EcmaScript 6 |
Description | Author | |||||||||||||||||||||||
This package can validate submitted input values in Node.js. Innovation Award
|
|
[![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Coverage Status][codecov-img]][codecov-url] [![David deps][david-image]][david-url] [![node version][node-image]][node-url]
[travis-image]: https://api.travis-ci.org/bitnbytesio/node-input-validator.svg?branch=master [travis-url]: https://travis-ci.org/bitnbytesio/node-input-validator?branch=master
[codecov-img]: https://codecov.io/gh/bitnbytesio/node-input-validator/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/bitnbytesio/node-input-validator
[david-image]: https://david-dm.org/bitnbytesio/node-input-validator.svg?style=flat-square&branch=master [david-url]: https://david-dm.org/bitnbytesio/node-input-validator?branch=master
[npm-image]: https://img.shields.io/npm/v/node-input-validator.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/node-input-validator [node-image]: https://img.shields.io/badge/node.js-%3E=_8.16-green.svg?style=flat-square [node-url]: http://nodejs.org/download/
Validation library for node.js
NIV (Node Input Validator) is a validation library for node.js. You can also extend library to add custom rules.
Note: For use case of any rule, please check test cases, If you have any doubt or confusion with documentation or rule behaviour.
npm i node-input-validator
const { Validator } = require('node-input-validator');
const v = new Validator(
{ name: '' },
{ name: 'required|minLength:5' },
);
v.check().then(function (matched) {
console.log(matched);
console.log(v.errors);
});
const { Validator } = require('node-input-validator');
app.post('login', function (req, res) {
const v = new Validator(req.body, {
email: 'required|email',
password: 'required'
});
v.check().then((matched) => {
if (!matched) {
res.status(422).send(v.errors);
}
});
});
const { Validator } = require('node-input-validator');
router.post('login', async (ctx) => {
const v = new Validator(ctx.request.body, {
email: 'required|email',
password: 'required'
});
const matched = await v.check();
if (!matched) {
ctx.status = 422;
ctx.body = v.errors;
return;
}
});
const niv = require('node-input-validator');
// keep this under your error handler
app.use(niv.koa());
// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
name: 'required|maxLength:50',
username: 'required|maxLength:15',
email: 'required|email',
password: 'required'
});
// validation passes
// do some code
// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
name: 'required|maxLength:50',
username: 'required|maxLength:15',
email: 'required|email',
password: 'required'
}, ctx.request.body);
// validation passes
// do some code
// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
name: 'required|maxLength:50',
username: 'required|maxLength:15',
email: 'required|email',
password: 'required'
}, ctx.request.body, { email: 'E-mail is required' });
// validation passes
// do some code
// if validation fails, this will auto abort request with status code 422 and errors in body
const v = await ctx.validator(ctx.request.body, {
name: 'required|maxLength:50',
username: 'required|maxLength:15',
email: 'required|email',
password: 'required'
});
// in case validation fails
if (v.fails()) {
ctx.status = 422;
ctx.body = v.errors;
return;
}
// do some code
const 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'
},
);
const matched = await v.check();
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();
Placeholder in messages, :attribute will be replaced with field/attribute name, :value with field value and :arg0, :arg1 ...n with arguments passed to rule.
const niv = require('node-input-validator');
/
* @param {Object} messages
* @param {string?=en} language
*/
niv.extendMessages({
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'
}, 'en');
const niv = require('node-input-validator');
//Note: Default language is English (en).
niv.addCustomMessages({
'username.required': 'When username attribute required rule failed.',
username: 'Default message for username attribute.'
});
You can easliy add messages in another language.
const niv = require('node-input-validator');
niv.extendMessages({
required: ':attribute ???? ???? ???? ???? ??????.',
}, 'pb');
const niv = require('node-input-validator');
niv.setLang('pb');
By default, Validator will run in bailable mode ie. break if some rule failed. You can change this behaviour:
const niv = require('node-input-validator');
niv.bailable(false);
Now instead of breaking, it will continues apply other rules.
{
name: [
{
rule: 'minLength',
message: '...',
},
{
rule: 'alpha',
message: '...',
}
]
}
To toggle multiple errors on specific instance only.
const niv = require('node-input-validator');
const v = new niv.Validator(inputs, rules);
v.bail(false);
You can also declare Nice Names / Custom Attributes names.
const niv = require('node-input-validator');
niv.niceNames({
phone: 'phone number',
dob: 'Date of Birth'
});
If your are editing other languages, set lang parameter.
const niv = require('node-input-validator');
niv.niceNames({
phone: 'phone number',
dob: 'Date of Birth'
},'fa');
In error messages you will get "phone number" instead of phone. For Example: In case required rule failed, Error message will be: The phone number field is mandatory.
const niv = require('node-input-validator');
const v = new niv.Validator(inputs, rules);
v.niceNames({
phone: 'phone number',
dob: 'Date of Birth'
});
This will only change attribute names for current instance.
// second params will be the instance of Validator
niv.extend('even', ({ value }) => {
if ((parseInt(value) % 2) == 0) {
return true;
}
return false;
});
const niv = require('node-input-validator');
niv.extend('sumOfFields', ({ value, args }, validator) => {
if (args.length !== 2) {
throw new Error('Invalid seed for rule sumOfFields');
}
const anotherValue = Number(validator.inputs[args[0]]);
const eq = Number(args[1]);
if ((Number(value) + anotherValue) !== eq) {
return false;
}
return true;
});
let v = new niv.Validator(
{ num1: '50', num2: '50' },
{ num1: 'sumOfFields:num2,100|required' },
);
let matched = await v.check();
assert.equal(matched, true);
// use this rules as unique:seed
// unique:<Mongoose Model>,<Field Name>,<ID to Ignore, This is optional>
const niv = require('node-input-validator');
const mongoose = require('mongoose');
niv.extend('unique', async ({ value, args }) => {
// default field is email in this example
const field = args[1] || 'email';
let condition = {};
condition[field] = value;
// add ignore condition
if (args[2]) {
condition['_id'] = { $ne: mongoose.Types.ObjectId(args[2]) };
}
let emailExist = await mongoose.model(args[0]).findOne(condition).select(field);
// email already exists
if (emailExist) {
return false;
}
return true;
});
// example usage of upper extended rule
new niv.Validator({
email: 'required|email|unique:User,email'
}, inputs);
// in case to ignore specific id
new niv.Validator({
email: 'required|email|unique:User,email,5c2f29e9cefa7718a54f8ff1'
}, inputs);
const niv = require('node-input-validator');
let v = new niv.Validator(
{ foo: 'bar'},
{ foo: ['required', 'string', ["minLength", 5]] },
);
let matched = await v.check();
assert.equal(matched, true);
v = new niv.Validator(
{ foo: 'bar'},
{ foo: ['required', 'string', "minLength:5" ] },
);
matched = await v.check();
assert.equal(matched, true);
You can check test cases for rule usage/examples.
required The field under validation cannot be left blank.
// should fail
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
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
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.
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.
new Validator(
{ email: '', username: '' },
{ email: 'requiredWithout:phone,pan', username: 'requiredWithout:email' },
);
accepted The field under validation must be yes, on, 1, or true.
accepted:seeds The field under validation must be accepted if value exists in provided seed.
after:YYYY-MM-DD The field under validation must be date after provided seed.
new Validator(
{ joining: '' },
{ joining: 'required|after:2018-02-10' },
);
alpha alpha:locale 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 alphaNumeric:locale The field under validation only contains letters and numbers.
array The field under validation must be an array.
arrayUnique <sub>Added in: v3.5</sub> The field under validation must be an array and must contains unique values. No need to use array rule. This rule will take care of that.
arrayUniqueObjects:attributes <sub>Added in: v3.5</sub> The field under validation must be an array and should have objects with unique attributes as per seed. No need to use array rule. This rule will take care of that.
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).
dateAfterToday:number,unit The field under validation must be a valid date after provided seed.
new Validator(
{ expiry: '2019-02-28' },
{ expiry: 'required|dateAfterToday:2,days' },
);
see moment docs(https://momentjs.com/docs/#/manipulating/add/) for supported units.
dateBeforeToday:number,unit The field under validation must be a valid date before provided seed.
let v = new Validator({valid:'2019-02-28'}, {valid:'required|dateBeforeToday:2,months'});
dateFormat:format The field under validation must match the given date format.
Note: use array of rules style declaration to deal with colon (:) in time formats.
new Validator(
{ dob: '' },
{ dob: 'required|dateFormat:YYYY-MM-DD' },
);
Check https://momentjs.com/docs/ for supported formats
dateiso <sub>Added in: v3.6</sub> The field under validation must be a valid iso date.
datetime <sub>Added in: v3.6</sub> The field under validation must match YYYY-MM-DD HH:mm:ss format.
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.
domain The field under validation must a qualified domain.
dimensions:seed <sub>Added in: v3.7</sub> The image under validation must meet the dimension constraints as specified by in seed.
new Validator(
req.body,
{ file: 'dimensions:minWidth=50,minHeight=50' },
);
const matched = await v.check();
assert.equal(matched, false);
Note: image mimes validation is required before.
Available constraints are: minWidth, maxWidth, minHeight, maxHeight, width, height.
email The field under validation must be formatted as an e-mail address.
equals The field under validation must be equal to given value.
gt:another_field <sub>Added in: v3.4</sub> The field under validation must be greater then another field value. This rule is for Numbers comparision.
gte:another_field <sub>Added in: v3.4</sub> The field under validation must be greater or equals to another field value. This rule is for Numbers comparision.
hash:algo The field under validation must be a valid hash as per provided seed.
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.
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.
length:max length:max,min <sub>Added in: v3.5</sub> The field under validation must be less then or equals to max seed provided in rule. In case of min,max seed, field under validation must be less or equals to max seed and less then min seed. Can only be used with strings|arrays or any other object that supports length (str.length) property.
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'});
lt:another_field <sub>Added in: v3.4</sub> The field under validation must be less then another field value. This rule is for Numbers comparision.
lte:another_field <sub>Added in: v3.4</sub> The field under validation must be less or equals to another field value. This rule is for Numbers comparision.
macAddress The field under validation should be a valid Mac Address.
max:seed The field under validation must be less than given value.
new Validator(
{ age: '' },
{ age: 'required|max:35' },
);
maxLength:seed The length of field under validation should be less than given value.
new Validator(
{ username: '' },
{ username: 'required|max:10' },
);
mime:seed The file under validation must have a MIME type corresponding to one of the listed extensions.
new Validator(
req.body,
{ file: 'required|mime:jpg,png' },
);
min The field under validation must be greater than given value.
minLength The length of field under validation should be greater than given value.
mongoId The field under validation should be a valid MongoDB ID.
notContains:seed The field under validation may not contains provided seeds.
notIn:seeds The field under validation must not exist in the given list of values.
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.
Note: Currently regex rules break on using colon (:) or pipe delimiters. Use array of rules style declaration instead of string.
new Validator(
req.body,
{ username: ['required', 'regex:[a-z]'] },
{ password: 'required|same:confirm_password' },
);
same The given field must match the field under validation.
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(Bytes),kb/k(KilloBytes),mb/m(MegaBytes),gb/g(GigaBytes).
// in below case, image file size should be under 4kb limit
new Validator({image:''}, {image:'required|size:4kb'});
// in below case, image file size should be between 1kb - 4kb
new Validator({image:''}, {image:'required|size:4kb,1kb'});
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 = new Validator(
{ name: '' },
{ '*': 'any:name,surname' },
);
v.check().then(function (matched) {
console.log(matched);
console.log(v.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 = new Validator(
{ username: 'arnold', password: 'arnold123' },
{ username: 'required', password: 'required' },
);
v.addPostRule((provider) => {
if (provider.inputs.password.indexOf(provider.inputs.username) >= 0) {
provider.error('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.
Partial Support.
Files (189) |
File | Role | Description | ||
---|---|---|---|---|
lib (1 file, 5 directories) | ||||
stubs (1 file) | ||||
test (11 files, 3 directories) | ||||
.eslintrc.json | Data | Auxiliary data | ||
.travis.yml | Data | Auxiliary data | ||
CHANGELOG.md | Data | Auxiliary data | ||
index.d.ts | Data | Auxiliary data | ||
jsconfig.json | Data | Auxiliary data | ||
package-lock.json | Data | Auxiliary data | ||
package.json | Data | Auxiliary data | ||
README.md | Doc. | Documentation |
Files (189) | / | lib |
Files (189) | / | lib | / | filters |
Files (189) | / | lib | / | postRules |
Files (189) | / | lib | / | rules |
File | Role | Description |
---|---|---|
accepted.js | Class | Class source |
acceptedIf.js | Class | Class source |
acceptedNotIf.js | Class | Class source |
activeUrl.js | Data | Auxiliary data |
after.js | Class | Class source |
afterOrEqual.js | Data | Auxiliary data |
alpha.js | Class | Class source |
alphaDash.js | Class | Class source |
alphaNumeric.js | Class | Class source |
array.js | Class | Class source |
arrayUnique.js | Class | Class source |
arrayUniqueObjects.js | Class | Class source |
ascii.js | Class | Class source |
base64.js | Class | Class source |
before.js | Class | Class source |
beforeOrEqual.js | Data | Auxiliary data |
between.js | Class | Class source |
boolean.js | Class | Class source |
confirmed.js | Class | Class source |
contains.js | Class | Class source |
creditCard.js | Class | Class source |
dateAfter.js | Class | Class source |
dateAfterToday.js | Class | Class source |
dateBefore.js | Class | Class source |
dateBeforeToday.js | Class | Class source |
dateFormat.js | Class | Class source |
dateiso.js | Class | Class source |
datetime.js | Class | Class source |
decimal.js | Class | Class source |
different.js | Data | Auxiliary data |
digits.js | Class | Class source |
digitsBetween.js | Class | Class source |
dimensions.js | Class | Class source |
domain.js | Class | Class source |
email.js | Class | Class source |
equals.js | Class | Class source |
gt.js | Class | Class source |
gte.js | Class | Class source |
hash.js | Class | Class source |
hex.js | Class | Class source |
hexColor.js | Class | Class source |
in.js | Class | Class source |
index.js | Aux. | Auxiliary script |
integer.js | Class | Class source |
ip.js | Class | Class source |
ipv4.js | Data | Auxiliary data |
ipv6.js | Data | Auxiliary data |
iso8601.js | Class | Class source |
json.js | Class | Class source |
latLong.js | Class | Class source |
length.js | Class | Class source |
lengthBetween.js | Class | Class source |
lt.js | Class | Class source |
lte.js | Class | Class source |
macAddress.js | Class | Class source |
max.js | Class | Class source |
maxLength.js | Class | Class source |
mime.js | Class | Class source |
min.js | Class | Class source |
minLength.js | Class | Class source |
mongoId.js | Class | Class source |
notContains.js | Class | Class source |
notIn.js | Class | Class source |
numeric.js | Class | Class source |
object.js | Class | Class source |
phoneNumber.js | Class | Class source |
regex.js | Class | Class source |
requiredIf.js | Class | Class source |
requiredNotIf.js | Class | Class source |
requiredWith.js | Class | Class source |
requiredWithout.js | Class | Class source |
same.js | Class | Class source |
size.js | Class | Class source |
sometimes.js | Class | Class source |
string.js | Class | Class source |
timezone.js | Data | Auxiliary data |
url.js | Class | Class source |
Files (189) | / | lib | / | util |
File | Role | Description |
---|---|---|
date.js | Class | Class source |
empty.js | Class | Class source |
messageParser.js | Class | Class source |
namedArgs.js | Class | Class source |
obj.js | Example | Example script |
ObjectIndex.js | Class | Class source |
sizeToBytes.js | Class | Class source |
str.js | Aux. | Auxiliary script |
Files (189) | / | test |
File | Role | Description | ||
---|---|---|---|---|
postRules (3 files) | ||||
rules (70 files) | ||||
stubs (2 files) | ||||
arrayRules.js | Example | Example script | ||
assert.js | Example | Example script | ||
async.js | Example | Example script | ||
edge.js | Example | Example script | ||
extend.js | Example | Example script | ||
inputs.js | Data | Auxiliary data | ||
nested.js | Example | Example script | ||
non-bailable.js | Example | Example script | ||
objects.js | Example | Example script | ||
rootArray.js | Example | Example script | ||
util.js | Example | Example script |
Files (189) | / | test | / | postRules |
File | Role | Description |
---|---|---|
all.js | Example | Example script |
any.js | Example | Example script |
function.js | Class | Class source |
Files (189) | / | test | / | rules |
File | Role | Description |
---|---|---|
accepted.js | Example | Example script |
acceptedIf.js | Example | Example script |
acceptedNotIf.js | Data | Auxiliary data |
alpha.js | Example | Example script |
alphaDash.js | Example | Example script |
alphaNumeric.js | Example | Example script |
array.js | Example | Example script |
arrayUnique.js | Example | Example script |
arrayUniqueObjects.js | Example | Example script |
ascii.js | Example | Example script |
base64.js | Example | Example script |
between.js | Example | Example script |
boolean.js | Example | Example script |
contains.js | Example | Example script |
creditCard.js | Example | Example script |
date.js | Example | Example script |
dateAfter.js | Example | Example script |
dateAfterToday.js | Example | Example script |
dateBefore.js | Example | Example script |
dateBeforeToday.js | Example | Example script |
dateFormat.js | Example | Example script |
dateiso.js | Example | Example script |
datetime.js | Example | Example script |
decimal.js | Example | Example script |
different.js | Example | Example script |
digits.js | Example | Example script |
digitsBetween.js | Example | Example script |
dimensions.js | Example | Example script |
domain.js | Example | Example script |
email.js | Example | Example script |
equals.js | Example | Example script |
gt.js | Example | Example script |
gte.js | Example | Example script |
hash.js | Example | Example script |
hex.js | Example | Example script |
hexColor.js | Example | Example script |
in.js | Example | Example script |
integer.js | Example | Example script |
ip.js | Example | Example script |
iso1801.js | Example | Example script |
json.js | Example | Example script |
latLong.js | Example | Example script |
length.js | Example | Example script |
lengthBetween.js | Example | Example script |
lt.js | Example | Example script |
lte.js | Example | Example script |
macAddress.js | Example | Example script |
max.js | Example | Example script |
maxLength.js | Example | Example script |
mime.js | Example | Example script |
min.js | Example | Example script |
minLength.js | Example | Example script |
mongoId.js | Example | Example script |
notContains.js | Example | Example script |
notIn.js | Example | Example script |
nullable.js | Data | Auxiliary data |
numeric.js | Example | Example script |
object.js | Example | Example script |
phoneNumber.js | Example | Example script |
regex.js | Example | Example script |
required.js | Example | Example script |
requiredIf.js | Example | Example script |
requiredNotIf.js | Example | Example script |
requiredWith.js | Example | Example script |
requiredWithout.js | Example | Example script |
same.js | Example | Example script |
size.js | Example | Example script |
sometimes.js | Example | Example script |
string.js | Example | Example script |
url.js | Example | Example script |
Files (189) | / | test | / | stubs |
File | Role | Description |
---|---|---|
file-big.jpg | Data | Auxiliary data |
file-small.png | Icon | Icon image |
Version Control | Unique User Downloads | Download Rankings | |||||||||||||||
100% |
|
|
Applications that use this package |
If you know an application of this package, send a message to the author to add a link here.