Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
@webiny/validation
Advanced tools
A simple data validation library, packed with frequently used validators.
A simple data validation library, packed with frequently used validators like required
, email
, url
, creditCard
etc.
yarn add @webiny/validation
Validation of data is performed asynchronously by default, like in the following example:
import { validation } from '@webiny/validation';
validation.validate(123, 'required,number,gt:20').then(() => {
// Value is valid
}).catch(e => {
// Value is invalid
});
Validators are specified by its name and in this case, there are three - required
, number
and gt
.
Since value is not empty, it is a number and is greater than 20, code execution will proceed regularly.
On the other hand, if one of the validator was not satisfied, an instance of ValidationError
would be thrown.
import { validation } from '@webiny/validation';
validation.validate(10, 'required,number,gt:20').catch(e => {
// Throws an Error with message "Value needs to be greater than 20.".
});
It is possible to provide as many validators as needed.
As seen in previous section, validators can accept additional arguments, which are divided by colon. The following validator simply states that value must be greater than 20:
gt:20
Some validators may even accept more than one arguments:
in:dog:cat:fish:bird
There is no limit on the number of passed arguments.
The following is a complete list of built-in validators, ready to be used immediately:
creditCard
email
eq
gt
gte
in
integer
lt
lte
maxLength
minLength
number
password
phone
required
url
More information about each can be found in the following sections.
Apart from built-in validators, there are cases where additional validators might be needed. The following example shows how to add a custom validator:
import { validation, ValidationError } from '@webiny/validation';
validation.setValidator('gender', value => {
if (['male', 'female'].includes(value)) {
return;
}
throw new ValidationError('Value needs to be "male" or "female".);
});
// Throws an instance of ValidationError error.
await validation.validate('none', 'gender');
As mentioned, validation by default is performed asynchronously. But if more suitable, it can also be performed synchronously:
import { validation } from '@webiny/validation';
// Throws an instance of ValidationError error.
validation.validateSync('parrot', 'in:cat:dog:fish:parrot');
// Success.
validation.validateSync('fish', 'in:cat:dog:fish:parrot');
The following example shows how to force ValidationError to be returned, instead of thrown:
import { validation } from '@webiny/validation';
const error = await validation.validate("", "required", { throw: false });
Once executed, an instance of ValidationError will be assigned to the error
constant.
packages-utils/@webiny/validation/src/validation.js:23-148
Main class of Validation library. Exported as a singleton instance, it offers methods for sync/async data validation and overwriting or adding new validators.
Examples
import { validation } from '@webiny/validation';
// `validation` is a preconfigured instance of Validation class.
// From here you can either add new validators or use it as-is.
packages-utils/@webiny/validation/src/validation.js:40-43
Add new validator.
Parameters
name
string Validator name.callable
Validator Validator function which throws a ValidationError if validation fails.Returns Validation
packages-utils/@webiny/validation/src/validation.js:50-55
Get validator function by name.
Parameters
name
string Validator name.Returns Validator A validator function.
packages-utils/@webiny/validation/src/validation.js:64-92
Asynchronously validates value.
Parameters
value
any Value to validate.validators
string A list of comma-separated validators (eg. required,number,gt:20).options
ValidateOptions Validation options.Returns Promise<(boolean | ValidationError)>
packages-utils/@webiny/validation/src/validation.js:101-129
Synchronously validates value.
Parameters
value
any Value to validate.validators
string A list of comma-separated validators (eg. required,number,gt:20).options
ValidateOptions Validation options.Returns Promise<(boolean | ValidationError)>
packages-utils/@webiny/validation/src/validationError.js:10-21
This class is used by validators to throw an error when value validation fails.
Parameters
message
string Error messagevalidator
string Validator that triggered this errorvalue
any Value that triggered this errorpackages-utils/@webiny/validation/src/validators/creditCard.js:17-54
Credit card validator. This validator will check if the given value is a credit card number.
Parameters
value
any This is the value that will be validated.Examples
import { validation } from '@webiny/validation';
validation.validate('notACreditCard', 'creditCard').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/email.js:17-27
Email validator. This validator checks if the given value is a valid email address.
Parameters
value
any This is the value that will be validated.Examples
import { validation } from '@webiny/validation';
validation.validate('email@gmail.com', 'email').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/eq.js:18-27
Equality validator. This validator checks if the given values are equal.
Parameters
value
any This is the value that will be validated.params
Array<string> This is the value to validate against. It is passed as a validator parameter: eq:valueToCompareWith
Examples
import { validation } from '@webiny/validation';
validation.validate('email@gmail.com', 'eq:another@gmail.com').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/gt.js:18-25
"Greater than" validator. This validator checks if the given values is greater than the min
value.
Parameters
value
any This is the value that will be validated.params
Array<string> This is the value to validate against. It is passed as a validator parameter: gt:valueToCompareAgainst
Examples
import { validation } from '@webiny/validation';
validation.validate(10, 'gt:100').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/gte.js:18-25
"Greater than or equals" validator. This validator checks if the given values is greater than or equal to the min
value.
Parameters
value
any This is the value that will be validated.min
any This is the value to validate against. It is passed as a validator parameter: gte:valueToCompareAgainst
Examples
import { validation } from '@webiny/validation';
validation.validate(10, 'gte:100').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/in.js:18-27
"In array" validator. This validator checks if the given values is greater than or equal to the min
value.
Parameters
value
any This is the value that will be validated.params
any This is the array of values to search in. It is passed as a validator parameter: in:1:2:3
. Array values are separated by :
.Examples
import { validation } from '@webiny/validation';
validation.validate(10, 'in:10:20:30').then(() => {
// Valid
}).catch(e => {
// Invalid
});
packages-utils/@webiny/validation/src/validators/number.js:11-19
This validator checks of the given value is a number
Parameters
value
anyReturns boolean
packages-utils/@webiny/validation/types.js:9-9
This type defines the validator function.
Parameters
value
any This is the value being validated.
parameters
Array<string> (Optional) This represents an array validator parameters.
Throws ValidationError
packages-utils/@webiny/validation/types.js:17-19
This is an object containing validation options.
Properties
throw
boolean Should validation throw on failure? Default: true.FAQs
A simple data validation library, packed with frequently used validators.
We found that @webiny/validation demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.