- Notifications
You must be signed in to change notification settings - Fork1
The validator-js library makes data validation in JavaScript very easy in both the browser and Node.js.
License
chantouchsek/validatorjs
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The ValidatorJs library makes data validation in JavaScript very easy in both the browser and Node.js. This library wasforked fromValidatorJs to re-write in typescript to add more rules andfeatures.
- Works in both the browser and Node.
- Readable and declarative validation rules.
- Error messages with multilingual support.
- CommonJS/Browserify support.
- ES6 support.
- Re-written in Typescript
pnpm add @chantouchsek/validatorjs
npm install @chantouchsek/validatorjs
yarn add @chantouchsek/validatorjs
import{Validator}from'@chantouchsek/validatorjs'constvalidation=newValidator(data,rules,options)
data {Object} - The data you want to validate
rules {Object} - Validation rules
options {Object} - Optional customoptions to return
- Options
- locale?: string | Optional passing locale from config
- confirmedReverse?: boolean | Optional showing error message on confirmation field instead of password
- customMessages?: Record<string, any> | Optional custom error messages to return
- customAttributes?: Record<string, any> | Optional custom attribute name to return
- defaultAttributeName?: Record<LangTypes, string> | Optional replace all :attribute property with languages provided
constdata={age:28,email:'johndoe@gmail.com',name:'John',}construles={age:'min:18',email:'required|email',name:'required',}constvalidation=newValidator(data,rules)validation.passes()// truevalidation.fails()// false
To apply validation rules to thedata object, use the same object key names for therules object.
constvalidation=newValidator({email:'not an email address.com',name:'D',},{email:'required|email',name:'size:3',},)validation.fails()// truevalidation.passes()// false// Error messagesvalidation.errors.first('email')// 'The email format is invalid.'validation.errors.get('email')// returns an array of all email error messages
constvalidation=newValidator({email:'not an email address.com',name:'D',},{email:'required|email',name:'size:3',},{defaultAttributeName:{en:'',ja:'この項目',},})validation.fails()// truevalidation.passes()// false// Error messagesvalidation.errors.first('email')// 'The field format is invalid.'validation.errors.first('email')// 'この項目は正しいメールアドレスを入力してください。'validation.errors.get('email')// returns an array of all email error messages
Nested objects can also be validated. There are two ways to declare validation rules for nested objects. The first wayis to declare the validation rules with a corresponding nested object structure that reflects the data. The second wayis to declare validation rules with flattened key names. For example, to validate the following data:
constdata={bio:{age:28,education:{primary:'Elementary School',secondary:'Secondary School',},},name:'John',}
We could declare our validation rules as follows:
constnested={bio:{age:'min:18',education:{primary:'string',secondary:'string',},},name:'required',}// ORconstflattened={'bio.age':'min:18','bio.education.primary':'string','bio.education.secondary':'string','name':'required',}
WildCards can also be validated.
constdata={users:[{bio:{age:28,education:{primary:'Elementary School',secondary:'Secondary School',},},name:'John',},],}
We could declare our validation rules as follows:
construles={'users.*.bio.age':'min:18','users.*.bio.education.primary':'string','users.*.bio.education.secondary':'string','users.*.name':'required',}
Validation rules do not have an implicit 'required'. If a field isundefined or an empty string, it will passvalidation. If you want a validation to fail for undefined or '', use therequired rule.
The field under validation must be yes, on, 1 or true. This is useful for validating "Terms of Service" acceptance.
The field under validation must be after the given date.
The field under validation must be after or equal to the given field
The field under validation must be entirely alphabetic characters.
The field under validation may have alphanumeric characters, as well as dashes and underscores.
The field under validation must be entirely alphanumeric characters.
The field under validation must be an array.
The field under validation must be before the given date.
The field under validation must be before or equal to the given date.
The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated inthe same fashion as the size rule.
The field under validation must be a boolean value of the formtrue
,false
,0
,1
,'true'
,'false'
,'0'
,'1'
,
The field under validation must have a matching field of foo_confirmation. For example, if the field under validation ispassword, a matching password_confirmation field must be present in the input.
The field under validation must be a valid date format which is acceptable by Javascript'sDate
object.
The field under validation must be numeric and must have an exact length of value.
The field under validation must be numeric and must have length between given min and max.
The given field must be different from the field under validation.
The field under validation must be formatted as an e-mail address.
The field under validation should be a hexadecimal format. Useful in combination with other rules, likehex|size:6
forhex color code validation.
The field under validation must be included in the given list of values. The field can be an array or string.
The field under validation must have an integer value.
Validate that an attribute is no greater than a given size
Note: Maximum checks are inclusive.
construles={phone:'required|digits|max:11',}constinput={phone:'01234567890',}// passes: true
construles={phone:'integer|max:16',}constinput={phone:'18',}// passes: false
Validate that an attribute is at least a given size.
Note: Minimum checks are inclusive.
construles={phone:'required|digits|min:11',}constinput={phone:'01234567890',}// passes: true
construles={phone:'integer|min:11',}constinput={phone:'18',}// passes: false
The field under validation must not be included in the given list of values.
Validate that an attribute is numeric. The string representation of a number will pass.
construles={amount:'numeric|digits:5',}
The field under validation must be present in the input data but can be empty.
Checks if the length of the String representation of the value is >
The field under validation must be present and not empty if the another field is equal to any value.
The field under validation must be present and not empty unless the another field is equal to any value.
The field under validation must be present and not empty only if any of the other specified fields are present.
The field under validation must be present and not empty only if all the other specified fields are present.
The field under validation must be present and not empty only when any of the other specified fields are not present.
The field under validation must be present and not empty only when all the other specified fields are not present.
In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:
construles={email:'sometimes|required|email',}
In the example above, the email field will only be validated if it is present in the input.
The given field must match the field under validation.
The field under validation must have a size matching the given value. For string data, value corresponds to the numberof characters. For numeric data, value corresponds to a given integer value.
The field under validation must be a string.
Validate that an attribute has a valid URL format
The field under validation must match the given regular expression.
Note: When using theregex
pattern, it may be necessary to specify rules in an array instead of using pipedelimiters, especially if the regular expression contains a pipe character. For each backward slash that you used inyour regex pattern, you must escape each one with another backward slash.
constvalidation=newValidator({name:'Doe',salary:'10,000.00',yearOfBirth:'1980',},{name:'required|size:3',salary:['required','regex:/^(?!0\\.00)\\d{1,3}(,\\d{3})*(\\.\\d\\d)?$/'],yearOfBirth:['required','regex:/^(19|20)[\\d]{2,2}$/'],},)validation.fails()// falsevalidation.passes()// true
constvalidation=newValidator({age:30,name:'',},{age:['required',{in:[29,30]}],name:[{required_if:['age',30]}],},)validation.fails()// truevalidation.passes()// false
Validator.register(name,callbackFn,errorMessage)
name {String} - The name of the rule.
callbackFn {Function} - Returns a boolean to represent a successful or failed validation.
errorMessage {String} - An optional string where you can specify a custom error message.:attribute insideerrorMessage will be replaced with the attribute name.
Validator.register('telephone',(value,requirement,attribute)=>{// requirement parameter defaults to nullreturnvalue.match(/^\d{3}-\d{3}-\d{4}$/)},'The :attribute phone number is not in the format XXX-XXX-XXXX.',)
Register an asynchronous rule which accepts apasses
callback:
Validator.registerAsync('username_available',(username,attribute,req,passes)=>{// do your database/api checks here etc// then call the `passes` method where appropriate:passes()// if username is availablepasses(false,'Username has already been taken.')// if username is not available})
Then call your validator usingcheckAsync
passingfails
andpasses
callbacks like so:
constvalidator=newValidator({username:'test123',},{username:'required|min:3|username_available',},)functionpasses(){// Validation passed}functionfails(){validator.errors.first('username')}validator.checkAsync(passes,fails)
Usevalidated()
method to retrieve only the validated data and to filter out attributes not found on rules provided.
constvalidation=newValidator({age:28,email:'johndoe@gmail.com',gender:'male',name:'John',},{age:'min:18',name:'required',},)validation.validated()// will return `{ "name": "John", "age": 28 }`
validated()
method will throw an error when current validation is failing.
constvalidation=newValidator({age:28,email:'johndoe@gmail.com',gender:'male',name:'John',},{age:'min:40',name:'required',},)validation.validated()// will throw `Error('Validation failed!')`
validated()
method also works with asynchronous validation. In this case,passes()
callback will receive only the validated data (without theattributes not found on rules provided) as the first argument.
constvalidation=newValidator({age:28,email:'johndoe@gmail.com',gender:'male',name:'John',},{age:'min:18',name:'required|some_async_rule',},)functionpasses(validated){console.log(validated)// will output `{ "name": "John", "age": 28 }` if `some_async_rule` validates `'John'`}functionfails(){// will be called if `some_async_rule` does not validate `'John'`}validation.validated(passes,fails)
This constructor will automatically generate error messages for validation rules that failed.
If there are errors, the Validator instance will have itserrors property object populated with the error messagesfor all failing attributes. The methods and properties on theerrors property object are:
returns the first error message for an attribute, false otherwise
returns an array of error messages for an attribute, or an empty array if there are no errors
returns an object containing all error messages for all failing attributes
returns true if error messages exist for an attribute, false otherwise
the number of validation errors
constvalidation=newValidator(input,rules)validation.errors.first('email')// returns first error message for email attributevalidator.errors.get('email')// returns an array of error messages for the email attribute
If you need a specific error message, and you don't want to override the default one, you can pass an override as thethird argument to the Validator object, just likewithLaravel.
constinput={name:'',}construles={name:'required',}constvalidation=newValidator(input,rules,{required:'You forgot to give a :attribute',})validation.passes()validation.errors.first('name')// returns 'You forgot to give a name'
Some validators have string and numeric versions. You can change them too.
constinput={username:'myusernameistoolong',}construles={username:'max:16',}constvalidation=newValidator(input,rules,{max:{string:'The :attribute is too long. Max length is :max.',},})validation.passes()validation.errors.first('username')// returns 'The username is too long. Max length is 16.'
You can even provide error messages on a per-attribute basis! Just set the message's key to 'validator.attribute'
constinput={email:'',name:''}construles={email:'required',name:'required'}constvalidation=newValidator(input,rules,{'required.email':'Without an :attribute we can\'t reach you!',})validation.passes()validation.errors.first('name')// returns 'The name field is required.'validation.errors.first('email')// returns 'Without an email we can\'t reach you!'
constvalidator=newValidator({form:{name:null}},{form:{age:'required',name:'required'}},{customAttributes:{form:{name:'Username'}},customMessages:{required:'The :attribute need to be filled.',},},)if(validator.fails())validator.errors.first('form.name')// "The Userame need to be filled."
To display a custom "friendly" attribute name in error messages, use.setAttributeNames()
constvalidator=newValidator({name:''},{name:'required'})validator.setAttributeNames({name:'custom_name'})if(validator.fails())validator.errors.first('name')// "The custom_name field is required."
Alternatively you can supply global custom attribute names in your lang with theattributes
property.
You can also configure a custom attribute formatter:
// Configure global formatter.Validator.setAttributeFormatter((attribute)=>{returnattribute.replace(/_/g,' ')})// Or configure formatter for particular instance.constvalidator=newValidator({first_name:''},{first_name:'required'})validator.setAttributeFormatter((attribute)=>{returnattribute.replace(/_/g,' ')})if(validator.fails())console.log(validator.errors.first('first_name'))// The first name field is required.
Note: by default all _ characters will be replaced with spaces.
Error messages are in English by default. To include another language in the browser, reference the language file in ascript tag and callValidator.useLang('lang_code')
.
<scriptsrc="dist/main.js"></script><scriptsrc="dist/lang/km.js"></script><script>Validator.useLang('km')</script>
In Node, it will automatically pick up on the language source files.
constValidator=require('validatorjs')Validator.useLang('km')
If you don't see support for your language, please add one tosrc/lang
!
You can also add your own custom language by callingsetMessages
:
Validator.setMessages('lang_code',{required:'The :attribute field is required.',})
Get the raw object of messages for the given language:
Validator.getMessages('lang_code')
Switch the default language used by the validator:
Validator.useLang('lang_code')
Get the default language being used:
Validator.getDefaultLang()// returns e.g. 'en'
Override default messages for language:
constmessages=Validator.getMessages('en')messages.required='Whoops, :attribute field is required.'Validator.setMessages('en',messages)
Copyright © 2020-Present Chantouch Sek
Released under the MIT license
ValidatorJs re-written by Chantouch Sek
E-Mail:chantouchsek.cs83@gmail.com
Twitter@DevidCs83
Website:Chantouch
About
The validator-js library makes data validation in JavaScript very easy in both the browser and Node.js.