Gathering detailed insights and metrics for @mongez/validator
Gathering detailed insights and metrics for @mongez/validator
Gathering detailed insights and metrics for @mongez/validator
Gathering detailed insights and metrics for @mongez/validator
npm install @mongez/validator
Typescript
Module System
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
13 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Jan 13, 2022
Latest Version
1.0.18
Package Id
@mongez/validator@1.0.18
Unpacked Size
60.57 kB
Size
8.80 kB
File Count
82
Cumulative downloads
Total Downloads
A Data Validation System For Nodejs And Browser.
Basically, this package provides a simple way to validate values regardless where it comes from, you pass the value, value props and validation rules and that's it.
yarn add @mongez/validator
Or
npm i @mongez/validator
Let's see an example then illustrate what's happening here.
1import { Validator, requiredRule } from '@mongez/validator'; 2 3const myValue = 'welcome'; 4 5const props = { 6 required: true, 7}; 8 9const rules = [requiredRule]; 10 11const validator = new Validator(myValue, props, rules); 12 13validator.validate(); 14 15if (validator.passes()) { 16 // do something, in this case it will pass as `myValue` has a value 17}
Now let's take it piece by piece.
We import our Validator
class that will validate our value.
Then we declared a dummy constant myValue
for demonstration only.
After that we instantiated a new object of our Validator
class, the constructor receives three arguments:
value
: The value that will be validated.props
: The properties of that must be matched with the given value.rules
: An array of rules that go through the value and validate it against the provided props.errorMessagesOverrides
: optional, to declare the error message for each invalid rule, we'll go with it later.Next, we called the validate
method to run the rules against the given value.
Finally we check whether the given value is valid using passes
method.
And that's it.
You may also set value, props and rules after creating new object.
1import { Validator, requiredRule } from '@mongez/validator'; 2 3const myValue = 'welcome'; 4 5const props = { 6 required: true, 7}; 8 9const rules = [requiredRule]; 10 11const validator = new Validator(); 12 13validator.setValue(myValue).setProps(props).setRules(rules); 14 15validator.validate(); 16 17if (validator.passes()) { 18 // do something, in this case it will pass as `myValue` has a value 19}
Another way to use validator by using validate
function directly.
1import { validate, requiredRule } from '@mongez/validator'; 2 3const myValue = 'welcome'; 4 5const props = { 6 required: true, 7}; 8 9const rules = [RequiredValue]; 10 11const validator = validate(myValue, props, rules); 12 13if (validator.passes()) { 14 // 15}
The function basically shortcuts the validate()
method step, so it instantiate the validator object and directly call validate
method.
Our previous examples will always provide a valid check that passes()
returns true, let's see an example with validation error.
1import { validate, requiredRule } from '@mongez/validator'; 2 3const emptyValue = ''; 4 5const props = { 6 required: true, 7}; 8 9const rules = [requiredRule]; 10 11const validator = validate(emptyValue, props, rules); 12 13if (validator.fails()) { 14 // 15 const error = validator.getError(); 16 17 console.log(error.errorMessage); // validation.required 18}
So fails
method will tells you that validation has failed, to get more information about the validation error, getError
will provide you with more details about the error.
getError
returns an object of RuleResponse
, an object for information about validation error.
1type RuleResponse = { 2 /** 3 * Determine if the rule will trigger an error 4 */ 5 hasError: boolean; 6 /** 7 * Set the error message that will be triggered if rule has any error 8 */ 9 errorMessage: string; 10 /** 11 * The error type of the input, i.e minLength, required, email... 12 */ 13 errorType: string; 14}
In our last example, error.errorMessage
returned validation.required
, the question here is, why?
Well, basically the validation package depends on Mongez Localization Using trans
method.
So if you've appended validation.required
key in translation list of Mongez Localization
then, the translated error message will be returned instead.
The package is shipped with about 10 most commonly used rules that you might need.
Let's see it one by one
The requiredRule
validates the given value that must not be empty.
required
false
string
| array
| object
| null
undefined
required
validation.required
Let's understand the previous criteria list to understand how rules work.
Required Prop
: means the required
prop must be in the props
to make this rule starts.Requires a value to validate
: means whether the rule needs to be a non empty value to start or not, in the required
rule it will be false, most of the other rules will be set to true
so the rule won't work unless there is a value.Evaluate
: the rule evaluation criteria and how it evaluates the value, which tells you when the rule will fail.Error Type
: the errorType
value in RuleResponse
object.Error Message
: the errorMessage
value in RuleResponse
object, all rules shipped with Mongez Validator depends on trans
function, so in the required
rule validation.required
will be translated if it has a matching translation string.The emailRule
validates the given value to be valid email pattern.
type
to be email
true
email
validation.invalidEmailAddress
An example of usage
1import { validate, emailRule } from '@mongez/validator'; 2 3const value = 'some-invalid-mail'; 4 5const props = { 6 type: 'email', 7}; 8 9const rules = [emailRule]; 10 11console.log(validate(value, props, rules).fails()); // true 12 13console.log(validate('hassanzohdy@gmail.com', props, rules).passes()); // true
The urlRule
validates the given value to be a valid url pattern.
url
true
url
validation.url
An example of usage
1import { validate, urlRule } from '@mongez/validator'; 2 3const value = 'some-invalid-mail'; 4 5const props = { 6 type: 'url', 7}; 8 9const rules = [urlRule]; 10 11console.log(validate(value, props, rules).fails()); // true 12console.log(validate('google.com', props, rules).passes()); // true 13console.log(validate('https://google.com', props, rules).passes()); // true 14console.log(validate('http://google.com', props, rules).passes()); // true 15console.log(validate('https://www.google.com', props, rules).passes()); // true 16console.log(validate('http://www.google.com', props, rules).passes()); // true
The minValue
validates the given value is equal to or more than the given min
prop.
min
true
min
prop.min
validation.min
An example of usage
1import { validate, minRule } from '@mongez/validator'; 2 3const value = 5; 4 5const props = { 6 min: 6, 7}; 8 9const rules = [minRule]; 10 11console.log(validate(value, props, rules).fails()); // true 12console.log(validate(6, props, rules).passes()); // true 13console.log(validate(7, props, rules).passes()); // true 14console.log(validate('6', props, rules).passes()); // true 15console.log(validate('7', props, rules).passes()); // true
Please note that this rule validates numbers and strings as well as it cast the given value using Number()
cast function.
The maxRule
validates the given value is equal to or less than the given max
prop.
max
true
max
prop.max
validation.max
An example of usage
1import { validate, maxRule } from '@mongez/validator'; 2 3const value = 7; 4 5const props = { 6 max: 6, 7}; 8 9const rules = [maxRule]; 10 11console.log(validate(value, props, rules).fails()); // true 12console.log(validate(6, props, rules).passes()); // true 13console.log(validate(5, props, rules).passes()); // true 14console.log(validate('6', props, rules).passes()); // true 15console.log(validate('5', props, rules).passes()); // true
Please note that this rule validates numbers and strings as well as it cast the given value using
Number()
cast function.
The minLengthRule
validates the given value length is equal to or more than the given minLength
prop.
minLength
true
minLength
propminLength
validation.minLength
An example of usage
1import { validate, minLengthRule } from '@mongez/validator'; 2 3const value = 'hello'; 4 5const props = { 6 minLength: 4, 7}; 8 9const rules = [minLengthRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12console.log(validate('tour', props, rules).passes()); // true 13console.log(validate('two', props, rules).passes()); // false
The lengthRule
validates the given value length is equal to the given length
prop.
length
true
length
prop.length
validation.length
An example of usage
1import { validate, lengthRule } from '@mongez/validator'; 2 3const value = 'hello'; 4 5const props = { 6 length: 4, 7}; 8 9const rules = [lengthRule]; 10 11console.log(validate(value, props, rules).passes()); // false 12console.log(validate('tour', props, rules).passes()); // true 13console.log(validate('two', props, rules).passes()); // false
The maxLengthRule
validates the given value length is equal to or less than the given maxLength
prop.
maxLength
true
maxLength
propmaxLength
validation.maxLength
An example of usage
1import { validate, maxLengthRule } from '@mongez/validator'; 2 3const value = 'hello'; 4 5const props = { 6 maxLength: 4, 7}; 8 9const rules = [maxLengthRule]; 10 11console.log(validate(value, props, rules).passes()); // false 12console.log(validate('tour', props, rules).passes()); // true 13console.log(validate('two', props, rules).passes()); // true
The numberRule
validates the given value as its being a numeric value, regardless its type either string or number.
type
to be number
true
number
validation.number
An example of usage
1import { validate, numberRule } from '@mongez/validator'; 2 3const value = '12'; 4 5const props = { 6 type: 'number', 7}; 8 9const rules = [numberRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12console.log(validate('12.5', props, rules).passes()); // true 13console.log(validate(12, props, rules).passes()); // true 14console.log(validate(12.5, props, rules).passes()); // true 15console.log(validate('12string', props, rules).passes()); // false
The integerRule
validates the given value as its being an integer value, regardless its type either string or number.
type
to be integer
true
integer
validation.integer
An example of usage
1import { validate, integerRule } from '@mongez/validator'; 2 3const value = '12'; 4 5const props = { 6 type: 'integer', 7}; 8 9const rules = [integerRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12console.log(validate(12, props, rules).passes()); // true 13console.log(validate(12.5, props, rules).passes()); // false 14console.log(validate('12.5', props, rules).passes()); // true 15console.log(validate('12string', props, rules).passes()); // false
The floatRule
validates the given value as its being an float value, regardless its type either string or number.
type
to be float
true
float
validation.float
Please note that any integers will be validated as invalid float number, use
numberRule
if you would like to accept both integers and floats.
An example of usage
1import { validate, floatRule } from '@mongez/validator'; 2 3const value = '12.5'; 4 5const props = { 6 type: 'float', 7}; 8 9const rules = [floatRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12console.log(validate(12.5, props, rules).passes()); // true 13console.log(validate(12, props, rules).passes()); // false 14console.log(validate('12.5string', props, rules).passes()); // false
The patternRule
validates the given value pattern against the given pattern
prop.
pattern
true
pattern
proppattern
validation.pattern
, you may also set patternError
prop instead.An example of usage
1import { validate, patternRule } from '@mongez/validator'; 2 3const value = "01140144893"; 4 5const props = { 6 pattern: /^01\d{9}$/ 7}; 8 9const rules = [patternRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12console.log(validate("0122555598", props, rules).passes()); // false 13console.log(validate("something", props, rules).passes()); // false // errorMessage: This field is not matching the pattern
To set the error pattern, add patternError
prop
1import { validate, patternRule } from '@mongez/validator'; 2 3const value = "01140144893"; 4 5const props = { 6 pattern: /^01\d{9}$/, 7 patternError: 'Mobile Number must start with 01 followed by 9 digits,' 8}; 9 10const rules = [patternRule]; 11 12console.log(validate(value, props, rules).passes()); // true 13console.log(validate("0122555598", props, rules).passes()); // false 14console.log(validate("something", props, rules).passes()); // false // errorMessage: Mobile Number must start with 01 followed by 9 digits,
The matchElementRule
validates the given value pattern against the value of another dom element using given match
prop which holds id
of the other element.
matchElement
true
matchElement
validation.matchElement
.An example of usage
1import { validate, matchElementRule } from '@mongez/validator'; 2 3const value = "123456789"; 4 5const props = { 6 matchElement: 'password', // id of password input 7}; 8 9const rules = [matchElementRule]; 10 11console.log(validate(value, props, rules).passes()); // true 12 13// if not matched then the error message will be `This field is not matched with password`
Please note that the
matchElement
prop contains the id of the other element to be matched with, the other element is expected to beHTMLInputElement
element.
To change the matching element name, pass matchText
to the props list, this is also auto translated using trans
1import { validate, matchElementRule } from '@mongez/validator'; 2 3const value = "123456789"; 4 5const props = { 6 matchElement: 'id_password', // id of password input 7 matchText: 'Password', 8}; 9 10const rules = [matchElementRule]; 11 12console.log(validate(value, props, rules).passes()); // true 13 14// if not matched then the error message will be `This field is not matched with Password`
You may also get all rules list in one array by importing rulesList
1import { rulesList } from '@mongez/validator'; 2 3// rulesList contains all available rules in the package.
Please note that rules are operated in the order they are inserted in the rules are, so if the minLengthRule
is set before maxLengthRule
then it will be evaluated according to that order.
1 2import { validate, minLengthRule, maxLengthRule } from '@mongez/validator'; 3 4const value = 'hello'; 5 6const props = { 7 minLength: 4, 8}; 9 10const rules = [minLengthRule, maxLengthRule]; 11 12validate(value, props, rules); 13 14// is not the same as 15 16const rules2 = [maxLengthRule, minLengthRule]; 17 18validate(value, props, rules);
You may also define your own rules based on your needs, let's try creating a new rule.
The following code snippet is written in Typescript for better illustration.
1// valid-username.ts 2 3import { Rule, RuleResponse } from '@mongez/validator'; 4 5const pattern = /^[a-zA-Z]+[a-zA-Z0-9]+$/; 6 7const rule: Rule = { 8 rule: "username", 9 requiresValue: true, 10 evaluate: (value, props): RuleResponse => { 11 const response: RuleResponse = { 12 errorType: "username", 13 hasError: pattern.test(value) === false, 14 errorMessage: trans("validation.invalidUsername"), 15 }; 16 17 return response; 18 } 19}; 20 21export default rule;
We create a rule that validates the value against pattern that accepts username starts with English letter(s) followed by English letters or digits.
Now we can use it in our validator.
1import usernameRule from './valid-username'; 2import { validate } from '@mongez/validator'; 3 4const props = { 5 username: true, 6}; 7 8const rules = [usernameRule]; 9 10console.log(validate('myNameIsHasan', props, rules).passes()); // true 11console.log(validate('12awa', props, rules).passes()); // false
Mongez Validator is shipped with two locales of translations en
for English Messages and ar
for Arabic Messages.
Just import the translation list you need and add it to Mongez localization
.
1import { extend } from '@mongez/localization'; 2import { enTranslation, arTranslation } from '@mongez/validator'; 3 4extend('en', enTranslation); 5extend('ar', arTranslation);
Now translation messages will be returned directly, here is the current translation messages for English language.
Available translations are
enTranslation
for English andarTranslation
for Arabic.
1const translation = { 2 validation: { 3 required: "This field is required", 4 invalidEmailAddress: "Invalid Email Address", 5 url: "Invalid Url Address", 6 min: "Value can not be lower than %d", 7 max: "Value can not be higher than %d", 8 match: "This field is not matched with %s", 9 length: "This field length must be %d characters", 10 minLength: "This field should have at least %d characters", 11 maxLength: "This field can not be more than %d characters", 12 pattern: "This field is not matching the pattern", 13 }, 14}
As we mentioned earlier in this document, you may set the error messages that overrides the default error messages, by passing it as 4rth argument in Validator
class or validate
function by using setMessagesOverrides
method.
setMessagesOverrides(object: {errorType: errorMessage }): Validator
1import { Validator, minLengthRule, patternRule } from '@mongez/validator';
2
3const value = "AS";
4
5const props = {
6 minLength: 3,
7 pattern: /^[a-z]+$/,
8};
9
10const rules = [minLengthRule, patternRule];
11
12const validator = new Validator(value, props, rules);
13
14validator.setMessagesOverrides({
15 minLength: 'Length must be at least 3 characters.',
16 pattern: 'Value must be written in lower case.',
17});
18
19validator.validate();
20
21console.log(validator.getErrorMessage()); // Length must be at least 3 characters.
By default, Validator stops the loop over the passes rules for the first rule that returns Invalid evaluation, you may tell Validator
to continue validating through all passed rules and return list of RuleResponse[]
using setErrorReturnMode
.
setErrorReturnMode('all' | 'first'): Validator
Default value: first
.
Please Note that this method can not be used with
validate
utility.
1import { Validator, minLengthRule, patternRule } from '@mongez/validator'; 2 3const value = "AS"; 4 5const props = { 6 minLength: 3, 7 pattern: /^[a-z]+$/, 8 patternError: 'Value must be written in lower case.', 9}; 10 11const rules = [minLengthRule, patternRule]; 12 13const validator = new Validator(value, props, rules); 14 15validator.setErrorReturnMode('all').validate(); 16 17console.log(validator.getErrors()); // returns an array of RuleResponse
Another good feature is to list the entire validation results for all rules, the getValidationResults
method returns an array that contains all rules responses wether there are errors or not.
1import { validate, minLengthRule, maxLengthRule } from '@mongez/validator'; 2 3const value = "welcome"; 4 5const props = { 6 minLength: 3, 7 maxLength: 5, 8}; 9 10const rules = [minLengthRule, maxLengthRule]; 11 12const validator = validate(value, props, rules); 13 14console.log(validator.getValidationResults()); // returns an array of RuleResponse[]
Output:
1[ 2 { 3 "errorType": "minLength", 4 "hasError": false, 5 "errorMessage": "validation.minLength" 6 }, 7 { 8 "errorType": "maxLength", 9 "hasError": true, 10 "errorMessage": "validation.maxLength" 11 } 12]
You may also use other methods directly to get a value instead of returning an entire RuleResponse
for example, such as:
Validator.getErrorMessage(): string
Get the error message of first invalid rule directly if error mode is set to first
.Validator.getErrorType(): string
Get the error type of first invalid rule directly if error mode is set to first
.Validator.getErrorsList(): object
Get list of errors as an object {errorType: errorMessage}
if error mode is set to all
.Each instance of Validator
trigger punch of events during the validation process, which are:
validating
: Triggered before validation starts.pass
: Triggered when all validation rules pass.fail
: Triggered when any of validation rules fail.done
: Triggered after validation ends wether succeeded or failed.Example of usage.
1import { Validator, minLengthRule, maxLengthRule } from '@mongez/validator'; 2 3const value = "welcome"; 4 5const props = { 6 minLength: 3, 7 maxLength: 5, 8}; 9 10const rules = [minLengthRule, maxLengthRule]; 11 12const validator = new Validator(value, props, rules); 13 14validator.on('pass', validator => { 15 // everything is valid :) 16}).on('fail', validator => { 17 // validation didn't go as expected 18}).on('done', validator => { 19 // validation has just ended 20});
Please note that
done
event is triggered beforepass
andfail
events.
You may reuse one validator later, but you'd probably need to reset it before using it again using reset
method.
As a final method, you can destroy the validator as it resets validator values and clears its registered events.
1 2import { Validator, minLengthRule, maxLengthRule } from '@mongez/validator'; 3 4const value = "welcome"; 5 6const props = { 7 minLength: 3, 8 maxLength: 5, 9}; 10 11const rules = [minLengthRule, maxLengthRule]; 12 13const validator = new Validator(value, props, rules); 14 15validator.on('pass', validator => { 16 // everything is valid :) 17}).on('fail', validator => { 18 // validation didn't go as expected 19}).on('done', validator => { 20 // validation has just ended 21}); 22 23validator.validate(); 24 25validator.destroy(); // clears events subscriptions and resets validator
minLength
maxLength
length
rules now validate arrays.unique
exists
and so on.No vulnerabilities found.
No security vulnerabilities found.
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year