node-input-validator package. I'm so sorry this, because node-input-validator package use async/await not suitable my project.
This project copy fromValidation Library
Validation library for node.js
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 document rule use and behaviour.
Installation
npm install --save input-validator-node
Usage
Simple Example
const v = ; let validator = name:'' name:'required|minLength:5'; validator;
Example usage in express application
const v = ; app
const v = ; router
Objects Validation
let v = 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 = v;
Array Validation
let v = roles: 'admin' 'manager' 'member' 'roles': 'required|array' 'roles.*': 'required|string' ; let matched = v;
let v = plan: price:'25'title:'OK' price:''title:'' price:'30' price:''title:'Title' 'plan': 'required|array' 'plan.*.price': 'required|integer' 'plan.*.title': 'required' ;let matched = v;
Array of rules
Usefull in case of using colon (:) / pipe delimiters in rules like dateFormat / regex.
let v = Validator;let matched = v;
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;
Add custom messages
//Note: Default language is English (en). Validator;
Add/Update rules default message in another language
Currenlty this package only support english, But you can easliy add messages in another language.
Validator;
Set default language
const validator = ;validator;
Using Custom Attribute Names
const validator = ; let v = ctxrequestbody phone:'required' dob: 'required' ; v;
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.
Add your own custom validation rules
Validator; Validator;
Example of using other fileds in rule
Validator; let v = num1: '50' num2: '50' num1: 'sumOfFields:num2,100|required' ; let matched = v; assert;
Some example of using database in rules
// use this rules as unique:seed// unique:<Mongoose Model>,<Field Name>,<ID to Ignore, This is optional> const Validator = ;const mongoose = ; Validator; // example usage of upper extended rule email: 'required|email|unique:User,email' inputs; // in case to ignore specific id email: 'required|email|unique:User,email,5c2f29e9cefa7718a54f8ff1' inputs;
For Koa2 Attach koa middleware
const validator = ; // keep this under your error handlerapp;
Then in controller
// if validation fails, this will auto abort request with status code 422 and errors in bodyctx; // validation passes// do some code
With custom inputs
// if validation fails, this will auto abort request with status code 422 and errors in bodyctx; // validation passes// do some code
With custom inputs and custom messages
// if validation fails, this will auto abort request with status code 422 and errors in bodyctx; // validation passes// do some code
In case you wants control over validator, Then use
// if validation fails, this will auto abort request with status code 422 and errors in bodyconst v = ctx; // in case validation failsif v ctxstatus = 422; ctxbody = verrors; return; // do some code
This method (ctx.validator(rules,inputs={}, messages={})) also support same options as like ctx.validate
Rules
You can check test cases for rules usage/examples.
required
The field under validation cannot be left blank.
// required rule validation failslet v = 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 16let v = 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 16let v = 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 = 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 = 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 = 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.
arrayUnique
Added in: v3.5
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
Added in: v3.5
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 = 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.
let v = 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 = 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.
let v = dob:'' dob:'required|dateFormat:YYYY-MM-DD';
Check https://momentjs.com/docs/ for supported formats
dateiso
Added in: v3.6
The field under validation must be a valid iso date.
datetime
Added in: v3.6
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.
let v = 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.
gt:another_field
Added in: v3.4
The field under validation must be greater then another field value. This rule is for Numbers comparision.
gte:another_field
Added in: v3.4
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.
let v = 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 = 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
Added in: v3.5
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 = age:'' age:'required|between:17,30';
lt:another_field
Added in: v3.4
The field under validation must be less then another field value. This rule is for Numbers comparision.
lte:another_field
Added in: v3.4
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.
let v = id: '00:14:22:01:23:45' id: 'required|macAddress' ;;
max
The field under validation must be less than given value.
let v = age:'' age:'required|max:35';
maxLength
The length of field under validation should be less than given value.
let v = 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 = age:'' age:'required|min:21';
minLength
The length of field under validation should be greater than given value.
let v = username:'' username:'required|max:10|min:5';
mongoId
The field under validation should be a valid MongoDB ID.
let v = 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 = 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.
Note: Currently regex rules break on using colon (:) or pipe delimiters. Use array of rules style declaration instead of string.
same
The given field must match the field under validation.
let v = 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 limitlet v = image:'' image:'required|size:4kb';
// in below case, image file size should be between 1kb - 4kblet v = image:'' image:'required|size:4kb,1kb';
let v = 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 = ; let validator = name:'' '*': 'any:name,surname'; validator;
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 = ; let v = username: 'arnold' password: 'arnold123' {}; v;
any
Any of the fields must be present in input.
all
All of the fields must be present in input.
Typescript Support
Partial Support.