Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
@chantouchsek/validatorjs
Advanced tools
The validator-js library makes data validation in JavaScript very easy in both the browser and Node.js.
The @chantouchsek/validatorjs library makes data validation in JavaScript very easy in both the browser and Node.js. This library was inspired by the Laravel framework's Validator and ValidatorJs
npm install @chantouchsek/validatorjs
yarn add @chantouchsek/validatorjs
<script src="@chantouchsek/validatorjs.js"></script>
// ES5
let Validator = require('@chantouchsek/validatorjs');
// ES6
import Validator from '@chantouchsek/validatorjs';
let options = {
input: {},
rules: {},
locale: 'km',
customMessages: {},
customAttributes: {}
}
let validation = new Validator(options);
data {Object} - The data you want to validate
rules {Object} - Validation rules
locale {string} - Validation locale
customMessages {Object} - Optional custom error messages to return
customAttributes {Object} - Optional custom error attributes to return
import Validator from '@chantouchsek/validatorjs'
let input = {
name: 'John',
email: 'johndoe@gmail.com',
age: 28
};
let rules = {
name: 'required',
email: 'required|email',
age: 'min:18'
};
let validation = new Validator({ input, rules, customMessages: {}, customAttributes: {} });
validation.passes(); // true
validation.fails(); // false
To apply validation rules to the data object, use the same object key names for the rules object.
let validation = new Validator({
input: {
name: 'D',
email: 'not an email address.com'
},
rules: {
name: 'size:3',
email: 'required|email'
}
});
validation.fails(); // true
validation.passes(); // false
// Error messages
validation.errors.first('email'); // 'The email format is invalid.'
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 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 input = {
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'
}
}
};
// OR
let flattened = {
'name': 'required',
'bio.age': 'min:18',
'bio.education.primary': 'string',
'bio.education.secondary': 'string'
};
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': 'required',
'users.*.bio.age': 'min:18',
'users.*.bio.education.primary': 'string',
'users.*.bio.education.secondary': 'string'
};
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.
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 alpha-numeric characters, as well as dashes and underscores.
The field under validation must be entirely alpha-numeric 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, numeric, and files are evaluated in the same fashion as the size rule.
The field under validation must be a boolean value of the form true
, 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 is password, a matching password_confirmation | passwordConfirmation field must be present in the input.
_confirmation
attribute, you need to provide an option called confirmedReverse
The field under validation must be a valid date format which is acceptable by Javascript's Date
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 than 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, like hex|size:6
for hex color code validation.
The field under validation must be greater than the given field. The two fields must be of the same type.
The field under validation must be greater than or equal to the given field. The two fields must be of the same type.
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.
The field under validation must be less than the given field. The two fields must be of the same type.
The field under validation must be less than or equal to the given field. The two fields must be of the same type.
Validate that an attribute is no greater than a given size
Note: Maximum checks are inclusive.
Validate that an attribute is at least a given size.
Note: Minimum checks are inclusive.
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.
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 anotherfield field is equal to any value.
The field under validation must be present and not empty unless the anotherfield 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 of 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 of the other specified fields are not present.
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 number of 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.
The field under must be meet the password.
Note: When using the regex
pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
For each backward slash that you used in your regex pattern, you must escape each one with another backward slash
. Note that vlidator uses the standard JavaScript RegExp flavor of regular expressions.
let validation = new Validator({
input: {
name: 'Doe',
salary: '10,000.00',
yearOfBirth: '1980'
},
rules: {
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(); // false
validation.passes(); // true
let validation = new Validator({
input: {
age: 30,
name: ''
},
rules: {
age: ['required', { 'in': [29, 30] }],
name: [{ required_if: ['age', 30] }]
}
});
validation.fails(); // true
validation.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 inside errorMessage will be replaced with the attribute name.
Validator.register('telephone', function(value, requirement, attribute) { // requirement parameter defaults to null
return value.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 a passes
callback:
Validator.registerAsync('username_available', function(username, attribute, req, passes) {
// do your database/api checks here etc
// then call the `passes` method where appropriate:
passes(); // if username is available
passes(false, 'Username has already been taken.'); // if username is not available
});
Then call your validator using checkAsync
passing fails
and passes
callbacks like so:
let validator = new Validator({
input: {
username: 'test123'
},
rules: {
username: 'required|min:3|username_available'
}
});
function passes() {
// Validation passed
}
function fails() {
validator.errors.first('username');
}
validator.checkAsync(passes, fails);
This constructor will automatically generate error messages for validation rules that failed.
If there are errors, the Validator instance will have its errors property object populated with the error messages for all failing attributes. The methods and properties on the errors 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, undefined otherwise
the number of validation errors
return true if there is any errors exist
fill the errors object, use for custom fill errors
to clear all errors
to clear the given attribute from errors
to clear the input target.name give provide in form
<input type='text' name='name' v-model='name' />
let validation = new Validator({input, rules});
validation.errors.first('email'); // returns first error message for email attribute
validator.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 the third argument to the Validator object, just like with Laravel.
let input = {
name: ''
};
let rules = {
name : 'required'
};
let options = {
input,
rules,
customMessages: {
required: 'You forgot to give a :attribute'
}
}
let validation = new Validator(options);
validation.errors.first('name'); // returns 'You forgot to give a name'
Some of the validators have string and numeric versions. You can change them too.
let input = {
username: 'myusernameistoolong'
};
let rules = {
username : 'max:16'
};
let options = {
input,
rules,
customMessages: {
max: {
string: 'The :attribute is too long. Max length is :max.'
}
}
}
let validation = new Validator(options);
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'
Attributes can be like below:
module.exports = {
regex: 'The :attribute format is invalid.',
attributes: {
'form.age': 'អាយុ',
name: 'ឈ្មោះ',
form: {
name: 'ឈ្មោះ',
gender: 'Sex'
}
}
}
let input = { name: '', email: '' };
let rules = { name : 'required', email : 'required' };
let customMessages = {
"required.email": "Without an :attribute we can't reach you!"
}
let options = {
input,
rules,
customMessages
}
let validation = new Validator(options);
validation.errors.first('name'); // returns 'The name field is required.'
validation.errors.first('email'); // returns 'Without an email we can\'t reach you!'
To display a custom "friendly" attribute name in error messages, use .setAttributeNames()
let validator = new Validator({
input: { name: '' },
rules: { 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 the attributes
property.
You can also configure a custom attribute formatter:
// Configure global formatter.
Validator.setAttributeFormatter(function(attribute) {
return attribute.replace(/_/g, ' ');
});
// Or configure formatter for particular instance.
let validator = new Validator({
input: { first_name: '' },
rules: { first_name: 'required' }
});
validator.setAttributeFormatter(function(attribute) {
return attribute.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 a script tag and call Validator.useLang('lang_code')
.
<script src="dist/@chantouchsek/validatorjs.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('@chantouchsek/validatorjs');
Validator.useLang('ru');
If you don't see support for your language, please add one to src/lang
!
You can also add your own custom language by calling setMessages
:
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:
let messages = Validator.getMessages('en');
messages.required = 'Whoops, :attribute field is required.';
Validator.setMessages('en', messages);
Copyright © 2020 Chantouch Sek
Released under the MIT license
@chantouchsek/validatorjs re-write by Chantouch Sek
E-Mail: chantouchsek.cs83@gmail.com
Twitter @DevidCs83
Website: bookingkh.com
FAQs
The validator.js library makes data validation in JavaScript very easy in both the browser and Node.js.
The npm package @chantouchsek/validatorjs receives a total of 584 weekly downloads. As such, @chantouchsek/validatorjs popularity was classified as not popular.
We found that @chantouchsek/validatorjs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.