validator-checker-js
v1.2.4
Published
The ValidatorJs library makes data validation in JavaScript very easy in both the browser and Node.js. This library was forked from [ValidatorJs](https://github.com/mikeerickson/validatorjs) to re-write in typescript to add more rules and features.
Downloads
238
Readme
ValidatorJs
The ValidatorJs library makes data validation in JavaScript very easy in both the browser and Node.js. This library was forked from ValidatorJs to re-write in typescript to add more rules and features.
Installation
Using npm:
npm install validator-checker-js@latestUsing yarn:
yarn add validator-checker-jsUsing pnpm:
pnpm add validator-checker-jsQuick Start
import Validator from "validator-checker-js";
const validator = new Validator({
name: ["required", "string"],
});
const result = validator.passes({
name: "John",
});
console.log(result);
// { state: true, data: { name: "John" } }Why use ValidatorJs?
- 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
Basic Usage
const validation = new Validator(rules, options);rules {Object} - Validation rules
options {Object} - Optional custom options {errors:{[nameofRule]:Errors}}
Example 1 - Passing Validation
let data = {
name: 'John',
email: '[email protected]',
age: 28,
};
let rules = {
name: ['required'],
email: ['required', 'email'],
age: [{ min: 18 }],
};
let validation = new Validator(rules);
validation.passes(data); // {state:true,data:{'name': 'John','email': '[email protected]','age': 28}}
validation.getErrors(data); // {}the result of passes function
if the state is true
data the valid data type that you can use
if the state is false
errors it as an object the define the the paths of the errors ant array of all the error messages
{
[errorPaths]:[
{
value:any,//the value of the path,
message:string,//the description of the error
}
]
}To apply validation rules to the data object, use the same object key names for the rules object.
Example 2 - Failing Validation
let validation = new Validator({
name: [{ max: 3 }],
email: ['required', 'email'],
});
validation.passes({
name: 'D',
email: 'not an email address.com',
}); // {'errors': {'email': [{'message': 'THIS IS NOT A VALID EMAIL', 'value': 'not an email address.com'}]}, 'state': false}
validation.getErrors({
name: 'D',
email: 'not an email address.com',
}); //{'email': [{'message': 'THIS IS NOT A VALID EMAIL', 'value': 'not an email address.com'}]}Nested Rules
Nested objects can also be validated. There are two ways to declare validation rules for nested objects. The first way is to declare the validation rules with a corresponding nested object structure that reflects the data. The second way is to declare validation rules with flattened key names. For example, to validate the following data:
let data = {
name: 'John',
bio: {
age: 28,
education: {
primary: 'Elementary School',
secondary: 'Secondary School',
},
},
};We could declare our validation rules as follows:
let nested = {
name: ['required'],
bio: {
age: [{ min: 18 }],
education: {
primary: ['string'],
secondary: ['string'],
},
},
};you can declare self validation for the path by adding . to the object:
let nested = {
name: ['required'],
bio: {
'.': ['required'], //here you can add some rules to control bio path
age: [{ min: 18 }],
education: {
primary: ['string'],
secondary: ['string'],
},
},
};WildCards Rules
WildCards can also be validated.
let data = {
users: [
{
name: 'John',
bio: {
age: 28,
education: {
primary: 'Elementary School',
secondary: 'Secondary School',
},
},
},
],
};We could declare our validation rules as follows:
let rules = {
users: [
{
name: ['string'],
bio: {
age: [{ min: 18 }],
primary: ['string'],
secondary: ['string'],
},
},
'array',
],
};Or if you want the data as a map object
let rules = {
users: [
{
name: ['string'],
bio: {
age: [{ min: 18 }],
primary: ['string'],
secondary: ['string'],
},
},
'object', //here you can specify the type of the object if it is map (object) or an array (array)
],
};you can add some rules to the users path by adding the rules after type element
let rules = {
users: [
{
name: ['string'],
bio: {
age: [{ min: 18 }],
primary: ['string'],
secondary: ['string'],
},
},
'object',
['required', { max: 20 }], // here you can specify the object
],
};you can specify some exceptions of the rules by adding the exception elemnts indexs
let rules = {
users: [
{
name: ['string'],
bio: {
age: [{ min: 18 }],
primary: ['string'],
secondary: ['string'],
},
},
'object',
{ '.': ['required', { max: 20 }], 0: ['string'], 1: ['integer'] },
],
};Array Validation Examples
Validate an array of strings:
let rules = {
friendsNames: [['string']],
};
let validator = new Validator(rules);
validator.passes({ friendsNames: ['ahmed', 'ali', 'osama', 'said'] });
// { state: true, data: { friendsNames: ['ahmed', 'ali', 'osama', 'said'] } }
validator.passes({ friendsNames: ['ahmed', 12, 231, 'osama', 'said'] });
// { state: false, errors: { friendsNames: [...] } }Validate an array with min/max constraints:
let rules = {
friends: [['string'], 'array', [{ min: 0 }, { max: 10 }]],
};
let validator = new Validator(rules);
validator.passes({ friends: ['ahmed', 'ali', 'osama'] });
// { state: true, data: { friends: ['ahmed', 'ali', 'osama'] } }Object Map Validation
Validate an object as a map (key-value pairs):
let rules = {
friendsNames: [['string'], 'object'],
};
let validator = new Validator(rules);
validator.passes({
friendsNames: {
name1: 'ahmed',
name2: 'osama',
name3: 'said',
},
});
// { state: true, data: { friendsNames: { name1: 'ahmed', name2: 'osama', name3: 'said' } } }
validator.passes({
friendsNames: {
1: 'ahmed',
2: 'osama',
3: 1234,
},
});
// { state: false, errors: { 'friendsNames.3': [...] } }Complex Nested Validation
Validate complex nested structures:
let rules = {
person: [
{
age: ['integer'],
friends: [['string'], 'array', [{ min: 0 }, { max: 10 }]],
},
'object',
],
};
let validator = new Validator(rules);
validator.passes({
person: { ahmed: { age: 12, friends: ['ahmed', 'ali'] } },
});
// { state: true, data: { person: { ahmed: { age: 12, friends: ['ahmed', 'ali'] } } } }
validator.passes({
person: { ahmed: { age: 12, friends: ['ahmed', 'ali', 'new friend'] } },
});
// { state: true, data: { person: { ahmed: { age: 12, friends: ['ahmed', 'ali', 'new friend'] } } } }Available Rules
Validation rules do not have an implicit 'required'. If a field is undefined or an empty string, it will pass validation. If you want a validation to fail for undefined or '', use the required rule.
accepted
The field under validation must be yes, on, 1 or true. This is useful for validating 'Terms of Service' acceptance.
after:date
The field under validation must be after the given date. -->
before:date
The field under validation must be before the given date. -->
date:date
The field under validation must be after or equal to the given field
alpha
The field under validation must be entirely alphabetic characters.
alpha_dash
The field under validation may have alpha-numeric characters, as well as dashes and underscores.
alpha_num
The field under validation must be entirely alpha-numeric characters.
array
The field under validation must be an array.
min,max
The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.
boolean
The field under validation must be a boolean value of the form true, false, 0, 1, 'true', 'false', '0'
, '1',
confirmed
The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.
isDate
The field under validation must be a valid date format which is acceptable by Javascript's Date object.
different:attribute
The given field must be different than the field under validation.
The field under validation must be formatted as an e-mail address.
in:[values]
The field under validation must be included in the given list of values. The field can be an array or string.
integer
The field under validation must have an integer value.
max:value
Validate that an attribute is no greater than a given size
Note: Maximum checks are inclusive.
Example 1 - Max validation
let rules = {
phone: ['required', 'numeric', { max: 11 }],
};
let input = {
phone: '01234567890',
};
// passes: trueExample 2 - Max validation
let rules = {
phone: ['integer', { max: 16 }],
};
let input = {
phone: '18',
};
// passes: falsemin:value
Validate that an attribute is at least a given size.
Note: Minimum checks are inclusive.
Example 1 - Min validation
let rules = {
phone: ['required', 'numeric', { min: 11 }],
};
let input = {
phone: '01234567890',
};
// passes: trueExample 2 - Min validation
let rules = {
phone: ['integer', { min: 11 }],
};
let input = {
phone: '18',
};
// passes: falsenot_in:[array of string]
The field under validation must not be included in the given list of values.
numeric
Validate that an attribute is numeric. The string representation of a number will pass.
required
Checks if the length of the String representation of the value is >
required_if:{path:string , value:any}
The field under validation must be present and not empty if the anotherfield field is equal to any value.
required_unless:{path:string , value:any}
The field under validation must be present and not empty unless the anotherfield field is equal to any value.
required_with:[paths]
The field under validation must be present and not empty only if any of the other specified fields are present.
required_with_all:[paths]
The field under validation must be present and not empty only if all of the other specified fields are present.
required_without:[paths]
The field under validation must be present and not empty only when any of the other specified fields are not present.
required_without_all:[paths]
The field under validation must be present and not empty only when all of the other specified fields are not present.
string
The field under validation must be a string.
url
Validate that an attribute has a valid URL format
regex:pattern
The field under validation must match the given regular expression.
Example 3 - Regex validation
let validation = new Validator({
name: [
'required',
{
min: 3,
max: 3,
},
],
salary: [
'required',
{ regex: /^(?!0\\.00)\\d{1,3}(,\\d{3})*(\\.\\d\\d)?$/ },
],
yearOfBirth: ['required', { regex: /^(19|20)[\\d]{2,2}$/ }],
});
validation.passes({
name: 'Doe',
salary: '10,000.00',
yearOfBirth: '1980',
}); // {state:true,data:{name: 'Doe',salary: '10,000.00',yearOfBirth: '1980'}}Example 4 - Type Checking Validation
let validation = new Validator({
age: ['required', { in: [29, 30] }],
name: [{ required_if: { path: 'age', value: 30 } }],
});
validation.passes({
age: 30,
name: '',
}); // {state:false}Register Custom Validation Rules
Validator.register(key, nameOrFunName, callbackFn, errorsObj);key {String} - The name of the rule that will be stored in the Rules and must be unique.
nameOrFunName {String|(val:unknown)=>boolean} - The name of the rule or the function that will check if the data pattern belongs to it.
callbackFn {Function} - Returns a string to represent a failed state and undefined to represent a successful. <Data>(value:unknown ,data:Data ,path:string,input:unknown,lang:LangTypes,errors:MessageStore<Data> )=>string|undefined
errorsObj {Object} - Error messages for different languages.
Example - Registering a Custom Rule
// First, extend the global Validator interface
declare global {
namespace Validator {
interface AvailableRules {
role: {
type: string;
path: { role: string };
errors: MessagesStore<{ role: string }>;
};
}
}
}
// Register the custom rule
Validator.register(
'role',
(value): value is { role: string } => {
return hasOwnProperty(value, 'role') && isString(value.role);
},
(teacherId, data) => {
if (!isString(teacherId)) return 'the userId is not a string';
},
{}
);
// Use the custom rule
const validator = new Validator({ val: [{ role: 'teacher' }] });Utility Functions
getValue
Extract a value from an object using a path string:
Validator.getValue({ name: 'ahmed' }, 'name'); // 'ahmed'
Validator.getValue({ person: ['ahmed', 'ali', 'osama'] }, 'person.*1'); // 'ali'
Validator.getValue({ person: { 1: 'ahmed' } }, 'person.1'); // 'ahmed'
Validator.getValue({ person: { '1': { name: ['ahmed'] } } }, 'person.1.name.*0'); // 'ahmed'getAllValues
Extract all values matching a path pattern:
Validator.getAllValues({ name: 'ahmed' }, 'name');
// { name: 'ahmed' }
Validator.getAllValues({ person: ['ahmed', 'ali', 'osama'] }, 'person.*:array');
// { 'person.*0': 'ahmed', 'person.*1': 'ali', 'person.*2': 'osama' }
Validator.getAllValues({ person: { 1: 'ahmed' } }, 'person.*:object');
// { 'person.1': 'ahmed' }
Validator.getAllValues(
{ person: { '1': { name: ['ahmed'] } } },
'person.*:object.name.*:array'
);
// { 'person.1.name.*0': 'ahmed' }validAttr
Validate and filter data to match the validation rules (removes unused properties):
const rules = {
name: ['string'],
age: ['integer'],
location: [['integer'], 'array', [{ min: 0 }, { max: 2 }]],
};
const validator = new Validator(rules);
validator.validAttr({ name: 'mahmoud', age: 12, location: [1, 2] });
// { name: 'mahmoud', age: 12, location: [1, 2] }
validator.validAttr({ name: 'mahmoud', age: 12, location: [1, 2], unusedAttr: 'unused' });
// { name: 'mahmoud', age: 12, location: [1, 2] } (unusedAttr is removed)inside
Type guard that checks if data matches validation rules and narrows TypeScript type:
const validator = new Validator({ name: 'string', age: 'integer' });
const data: unknown = { name: 'John', age: 25 };
if (validator.inside(data)) {
// data is now typed as { name: string; age: number }
console.log(data.name); // TypeScript knows this is a string
}Custom Attribute Names
Validate One Value
Validate a single value against a specific rule:
const validator = new Validator({ name: 'string' });
const result1 = validator.validate('ali', 'string');
// undefined (validation passed)
const result2 = validator.validate(1234, 'string');
// { message: 'THE TYPE OF INPUT IS NOT STRING', value: 1234 }value {unknown} - The value that you want to validate.
ruleData {RuleNames} - The rule description that you want to validate like 'string' or {min:20}.
lang {LangTypes} optional :the displaying message language
Asynchronous Validation
Use async validation when your validation rules include async operations (e.g., database checks, API calls):
const validator = new Validator({ email: ['required'], password: ['required'] });
const result = await validator.asyncPasses({ email: '[email protected]', password: '1234' });
// { state: true, data: { email: '[email protected]', password: '1234' } }
const errors = await validator.asyncGetErrors({ email: null });
// { password: [{ message: 'the input value is not exist', value: undefined }] }Register an asynchronous rule which accepts a passes callback:
Validator.registerAsync(
'username_available',
'username_available',
async function (username, data, path, input, lang, errors) {}
);Then call your validator using asyncPasses or asyncGetErrors:
let validator = new Validator({
username: ['required', 'min:3', 'username_available'],
});
validator
.asyncPasses({ username: 'username' })
.then((res) => {})
.catch((err) => {});
validator
.asyncGetErrors({ username: 'username' })
.then((res) => {})
.catch((err) => {});Language Support
Error messages are in English by default. To include another language in the browser, reference the language file in a script tag and call Validator.useLang('lang_code').
<script src="dist/validator.js"></script>
<script src="dist/lang/ru.js"></script>
<script>
Validator.useLang('es');
</script>In Node, it will automatically pickup on the language source files.
let Validator = require('validator-checker-js');
Validator.useLang('ru');You can add your own custom language in initialization by add your custom errors in the options:
const validator = new Validator(
{},
{
errors: {
required: { en: 'The :attribute field is required.' },
},
}
);Get the raw object of messages for the given language:
validator.errors.required;Switch the default language used by the validator:
Validator.useLang('lang_code');Get the default language being used:
Validator.getDefaultLang(); // returns e.g. 'en'Get specific errors message by adding lang attribute to the passes or getErrors function:
validator.getErrors(data, 'lang_code');Override default messages for language:
let messages = Validator.Rules.required;
messages.en = 'my new custom message for required rule';TypeScript Support
This library is written in TypeScript and provides full type safety. The validator automatically infers types based on your validation rules:
import Validator from 'validator-checker-js';
// Simple type inference
const validator1 = new Validator({ name: 'string' });
const result1 = validator1.passes({ name: 'ali' });
if (result1.state) {
// result1.data is typed as { name: string | undefined } | undefined
console.log(result1.data.name); // TypeScript knows this is a string
}
// Complex type inference
const validator2 = new Validator({
person: [{ age: ['integer'], friends: [['string'], 'array', [{ min: 0 }, { max: 10 }]] }, 'object']
});
const result2 = validator2.passes({
person: { ahmed: { age: 12, friends: ['ahmed', 'ali'] } }
});
if (result2.state) {
// TypeScript knows the exact structure of result2.data
}The library also provides type guards:
const validator = new Validator({ name: 'string', age: 'integer' });
const data: unknown = { name: 'John', age: 25 };
if (validator.inside(data)) {
// data is now typed as { name: string; age: number }
console.log(data.name); // TypeScript knows this is a string
}Credits
validatorjs created by Imam Ashour
E-Mail: [email protected] Website: emam546.github.io
