Gathering detailed insights and metrics for @rc-component/async-validator
Gathering detailed insights and metrics for @rc-component/async-validator
Gathering detailed insights and metrics for @rc-component/async-validator
Gathering detailed insights and metrics for @rc-component/async-validator
npm install @rc-component/async-validator
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
8 Stars
340 Commits
6 Forks
2 Watching
3 Branches
24 Contributors
Updated on 04 Nov 2024
TypeScript (99.75%)
JavaScript (0.25%)
Cumulative downloads
Total Downloads
Last day
1.5%
112,997
Compared to previous day
Last week
4.9%
619,513
Compared to previous week
Last month
16.1%
2,499,474
Compared to previous month
Last year
4,482,442.2%
11,789,086
Compared to previous year
Validate form asynchronous. A variation of https://github.com/freeformsystems/async-validate
1npm i @rc-component/async-validator
Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to the validate
method of the schema:
1import Schema from '@rc-component/async-validator'; 2const descriptor = { 3 name: { 4 type: 'string', 5 required: true, 6 validator: (rule, value) => value === 'muji', 7 }, 8 age: { 9 type: 'number', 10 asyncValidator: (rule, value) => { 11 return new Promise((resolve, reject) => { 12 if (value < 18) { 13 reject('too young'); // reject with error message 14 } else { 15 resolve(); 16 } 17 }); 18 }, 19 }, 20}; 21const validator = new Schema(descriptor); 22validator.validate({ name: 'muji' }, (errors, fields) => { 23 if (errors) { 24 // validation failed, errors is an array of all errors 25 // fields is an object keyed by field name with an array of 26 // errors per field 27 return handleErrors(errors, fields); 28 } 29 // validation passed 30}); 31 32// PROMISE USAGE 33validator 34 .validate({ name: 'muji', age: 16 }) 35 .then(() => { 36 // validation passed or without error message 37 }) 38 .catch(({ errors, fields }) => { 39 return handleErrors(errors, fields); 40 });
1function(source, [options], callback): Promise
source
: The object to validate (required).options
: An object describing processing options for the validation (optional).callback
: A callback function to invoke when validation completes (optional).The method will return a Promise object like:
then()
,validation passedcatch({ errors, fields })
,validation failed, errors is an array of all errors, fields is an object keyed by field name with an array of errors per fieldsuppressWarning
: Boolean, whether to suppress internal warning about invalid value.
first
: Boolean, Invoke callback
when the first validation rule generates an error,
no more validation rules are processed.
If your validation involves multiple asynchronous calls (for example, database queries) and you only need the first error use this option.
firstFields
: Boolean|String[], Invoke callback
when the first validation rule of the specified field generates an error,
no more validation rules of the same field are processed. true
means all fields.
Rules may be functions that perform validation.
1function(rule, value, callback, source, options)
rule
: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a field
property with the name of the field being validated.value
: The value of the source object property being validated.callback
: A callback function to invoke once validation is complete. It expects to be passed an array of Error
instances to indicate validation failure. If the check is synchronous, you can directly return a false
or Error
or Error Array
.source
: The source object that was passed to the validate
method.options
: Additional options.options.messages
: The object containing validation error messages, will be deep merged with defaultMessages.The options passed to validate
or asyncValidate
are passed on to the validation functions so that you may reference transient data (such as model references) in validation functions. However, some option names are reserved; if you use these properties of the options object they are overwritten. The reserved properties are messages
, exception
and error
.
1import Schema from '@rc-component/async-validator';
2const descriptor = {
3 name(rule, value, callback, source, options) {
4 const errors = [];
5 if (!/^[a-z0-9]+$/.test(value)) {
6 errors.push(
7 new Error(util.format('%s must be lowercase alphanumeric characters', rule.field)),
8 );
9 }
10 return errors;
11 },
12};
13const validator = new Schema(descriptor);
14validator.validate({ name: 'Firstname' }, (errors, fields) => {
15 if (errors) {
16 return handleErrors(errors, fields);
17 }
18 // validation passed
19});
It is often useful to test against multiple validation rules for a single field, to do so make the rule an array of objects, for example:
1const descriptor = { 2 email: [ 3 { type: 'string', required: true, pattern: Schema.pattern.email }, 4 { 5 validator(rule, value, callback, source, options) { 6 const errors = []; 7 // test if email address already exists in a database 8 // and add a validation error to the errors array if it does 9 return errors; 10 }, 11 }, 12 ], 13};
Indicates the type
of validator to use. Recognised type values are:
string
: Must be of type string
. This is the default type.
number
: Must be of type number
.boolean
: Must be of type boolean
.method
: Must be of type function
.regexp
: Must be an instance of RegExp
or a string that does not generate an exception when creating a new RegExp
.integer
: Must be of type number
and an integer.float
: Must be of type number
and a floating point number.array
: Must be an array as determined by Array.isArray
.object
: Must be of type object
and not Array.isArray
.enum
: Value must exist in the enum
.date
: Value must be valid as determined by Date
url
: Must be of type url
.hex
: Must be of type hex
.email
: Must be of type email
.any
: Can be any type.The required
rule property indicates that the field must exist on the source object being validated.
The pattern
rule property indicates a regular expression that the value must match to pass validation.
A range is defined using the min
and max
properties. For string
and array
types comparison is performed against the length
, for number
types the number must not be less than min
nor greater than max
.
To validate an exact length of a field specify the len
property. For string
and array
types comparison is performed on the length
property, for the number
type this property indicates an exact match for the number
, ie, it may only be strictly equal to len
.
If the len
property is combined with the min
and max
range properties, len
takes precedence.
Since version 3.0.0 if you want to validate the values
0
orfalse
insideenum
types, you have to include them explicitly.
To validate a value from a list of possible values use the enum
type with a enum
property listing the valid values for the field, for example:
1const descriptor = { 2 role: { type: 'enum', enum: ['admin', 'user', 'guest'] }, 3};
It is typical to treat required fields that only contain whitespace as errors. To add an additional test for a string that consists solely of whitespace add a whitespace
property to a rule with a value of true
. The rule must be a string
type.
You may wish to sanitize user input instead of testing for whitespace, see transform for an example that would allow you to strip whitespace.
If you need to validate deep object properties you may do so for validation rules that are of the object
or array
type by assigning nested rules to a fields
property of the rule.
1const descriptor = { 2 address: { 3 type: 'object', 4 required: true, 5 fields: { 6 street: { type: 'string', required: true }, 7 city: { type: 'string', required: true }, 8 zip: { type: 'string', required: true, len: 8, message: 'invalid zip' }, 9 }, 10 }, 11 name: { type: 'string', required: true }, 12}; 13const validator = new Schema(descriptor); 14validator.validate({ address: {} }, (errors, fields) => { 15 // errors for address.street, address.city, address.zip 16});
Note that if you do not specify the required
property on the parent rule it is perfectly valid for the field not to be declared on the source object and the deep validation rules will not be executed as there is nothing to validate against.
Deep rule validation creates a schema for the nested rules so you can also specify the options
passed to the schema.validate()
method.
1const descriptor = { 2 address: { 3 type: 'object', 4 required: true, 5 options: { first: true }, 6 fields: { 7 street: { type: 'string', required: true }, 8 city: { type: 'string', required: true }, 9 zip: { type: 'string', required: true, len: 8, message: 'invalid zip' }, 10 }, 11 }, 12 name: { type: 'string', required: true }, 13}; 14const validator = new Schema(descriptor); 15 16validator.validate({ address: {} }).catch(({ errors, fields }) => { 17 // now only errors for street and name 18});
The parent rule is also validated so if you have a set of rules such as:
1const descriptor = { 2 roles: { 3 type: 'array', 4 required: true, 5 len: 3, 6 fields: { 7 0: { type: 'string', required: true }, 8 1: { type: 'string', required: true }, 9 2: { type: 'string', required: true }, 10 }, 11 }, 12};
And supply a source object of { roles: ['admin', 'user'] }
then two errors will be created. One for the array length mismatch and one for the missing required array entry at index 2.
The defaultField
property can be used with the array
or object
type for validating all values of the container.
It may be an object
or array
containing validation rules. For example:
1const descriptor = { 2 urls: { 3 type: 'array', 4 required: true, 5 defaultField: { type: 'url' }, 6 }, 7};
Note that defaultField
is expanded to fields
, see deep rules.
Sometimes it is necessary to transform a value before validation, possibly to coerce the value or to sanitize it in some way. To do this add a transform
function to the validation rule. The property is transformed prior to validation and returned as promise result or callback result when pass validation.
1import Schema from '@rc-component/async-validator'; 2const descriptor = { 3 name: { 4 type: 'string', 5 required: true, 6 pattern: /^[a-z]+$/, 7 transform(value) { 8 return value.trim(); 9 }, 10 }, 11}; 12const validator = new Schema(descriptor); 13const source = { name: ' user ' }; 14 15validator.validate(source) 16 .then((data) => assert.equal(data.name, 'user')); 17 18validator.validate(source,(errors, data)=>{ 19 assert.equal(data.name, 'user')); 20});
Without the transform
function validation would fail due to the pattern not matching as the input contains leading and trailing whitespace, but by adding the transform function validation passes and the field value is sanitized at the same time.
Depending upon your application requirements, you may need i18n support or you may prefer different validation error messages.
The easiest way to achieve this is to assign a message
to a rule:
1{ name: { type: 'string', required: true, message: 'Name is required' } }
Message can be any type, such as jsx format.
1{ name: { type: 'string', required: true, message: '<b>Name is required</b>' } }
Message can also be a function, e.g. if you use vue-i18n:
1{ name: { type: 'string', required: true, message: () => this.$t( 'name is required' ) } }
Potentially you may require the same schema validation rules for different languages, in which case duplicating the schema rules for each language does not make sense.
In this scenario you could just provide your own messages for the language and assign it to the schema:
1import Schema from '@rc-component/async-validator'; 2const cn = { 3 required: '%s 必填', 4}; 5const descriptor = { name: { type: 'string', required: true } }; 6const validator = new Schema(descriptor); 7// deep merge with defaultMessages 8validator.messages(cn); 9...
If you are defining your own validation functions it is better practice to assign the message strings to a messages object and then access the messages via the options.messages
property within the validation function.
You can customize the asynchronous validation function for the specified field:
1const fields = { 2 asyncField: { 3 asyncValidator(rule, value, callback) { 4 ajax({ 5 url: 'xx', 6 value: value, 7 }).then( 8 function (data) { 9 callback(); 10 }, 11 function (error) { 12 callback(new Error(error)); 13 }, 14 ); 15 }, 16 }, 17 18 promiseField: { 19 asyncValidator(rule, value) { 20 return ajax({ 21 url: 'xx', 22 value: value, 23 }); 24 }, 25 }, 26};
You can custom validate function for specified field:
1const fields = { 2 field: { 3 validator(rule, value, callback) { 4 return value === 'test'; 5 }, 6 message: 'Value is not equal to "test".', 7 }, 8 9 field2: { 10 validator(rule, value, callback) { 11 return new Error(`${value} is not equal to 'test'.`); 12 }, 13 }, 14 15 arrField: { 16 validator(rule, value) { 17 return [new Error('Message 1'), new Error('Message 2')]; 18 }, 19 }, 20};
1import Schema from '@rc-component/async-validator'; 2Schema.warning = function () {};
or
1globalThis.ASYNC_VALIDATOR_NO_WARNING = 1;
true
Use enum
type passing true
as option.
1{ 2 type: 'enum', 3 enum: [true], 4 message: '', 5}
1npm test
1npm run coverage
Open coverage/ dir
Everything is MIT.
No vulnerabilities found.
No security vulnerabilities found.