Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

validate form asynchronous

License

NotificationsYou must be signed in to change notification settings

yiminghe/async-validator

Repository files navigation

NPM versionbuild statusTest coveragenode versionnpm downloadnpm bundle size (minified + gzip)

Validate form asynchronous. A variation ofhttps://github.com/freeformsystems/async-validate

Install

npm i async-validator

Usage

Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to thevalidate method of the schema:

importSchemafrom'async-validator';constdescriptor={name:{type:'string',required:true,validator:(rule,value)=>value==='muji',},age:{type:'number',asyncValidator:(rule,value)=>{returnnewPromise((resolve,reject)=>{if(value<18){reject('too young');// reject with error message}else{resolve();}});},},};constvalidator=newSchema(descriptor);validator.validate({name:'muji'},(errors,fields)=>{if(errors){// validation failed, errors is an array of all errors// fields is an object keyed by field name with an array of// errors per fieldreturnhandleErrors(errors,fields);}// validation passed});// PROMISE USAGEvalidator.validate({name:'muji',age:16}).then(()=>{// validation passed or without error message}).catch(({ errors, fields})=>{returnhandleErrors(errors,fields);});

API

Validate

function(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 passed
  • catch({ 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 field

Options

  • suppressWarning: Boolean, whether to suppress internal warning about invalid value.

  • first: Boolean, Invokecallback 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[], Invokecallback 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

Rules may be functions that perform validation.

function(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 afield 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 ofError instances to indicate validation failure. If the check is synchronous, you can directly return afalse orError orError Array.
  • source: The source object that was passed to thevalidate method.
  • options: Additional options.
  • options.messages: The object containing validation error messages, will be deep merged with defaultMessages.

The options passed tovalidate orasyncValidate 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 aremessages,exception anderror.

importSchemafrom'async-validator';constdescriptor={name(rule,value,callback,source,options){consterrors=[];if(!/^[a-z0-9]+$/.test(value)){errors.push(newError(util.format('%s must be lowercase alphanumeric characters',rule.field),));}returnerrors;},};constvalidator=newSchema(descriptor);validator.validate({name:'Firstname'},(errors,fields)=>{if(errors){returnhandleErrors(errors,fields);}// validation passed});

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:

constdescriptor={email:[{type:'string',required:true,pattern:Schema.pattern.email},{validator(rule,value,callback,source,options){consterrors=[];// test if email address already exists in a database// and add a validation error to the errors array if it doesreturnerrors;},},],};

Type

Indicates thetype of validator to use. Recognised type values are:

  • string: Must be of typestring.This is the default type.
  • number: Must be of typenumber.
  • boolean: Must be of typeboolean.
  • method: Must be of typefunction.
  • regexp: Must be an instance ofRegExp or a string that does not generate an exception when creating a newRegExp.
  • integer: Must be of typenumber and an integer.
  • float: Must be of typenumber and a floating point number.
  • array: Must be an array as determined byArray.isArray.
  • object: Must be of typeobject and notArray.isArray.
  • enum: Value must exist in theenum.
  • date: Value must be valid as determined byDate
  • url: Must be of typeurl.
  • hex: Must be of typehex.
  • email: Must be of typeemail.
  • any: Can be any type.

Required

Therequired rule property indicates that the field must exist on the source object being validated.

Pattern

Thepattern rule property indicates a regular expression that the value must match to pass validation.

Range

A range is defined using themin andmax properties. Forstring andarray types comparison is performed against thelength, fornumber types the number must not be less thanmin nor greater thanmax.

Length

To validate an exact length of a field specify thelen property. Forstring andarray types comparison is performed on thelength property, for thenumber type this property indicates an exact match for thenumber, ie, it may only be strictly equal tolen.

If thelen property is combined with themin andmax range properties,len takes precedence.

Enumerable

Since version 3.0.0 if you want to validate the values0 orfalse insideenum types, you have to include them explicitly.

To validate a value from a list of possible values use theenum type with aenum property listing the valid values for the field, for example:

constdescriptor={role:{type:'enum',enum:['admin','user','guest']},};

Whitespace

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 awhitespace property to a rule with a value oftrue. The rule must be astring type.

You may wish to sanitize user input instead of testing for whitespace, seetransform for an example that would allow you to strip whitespace.

Deep Rules

If you need to validate deep object properties you may do so for validation rules that are of theobject orarray type by assigning nested rules to afields property of the rule.

constdescriptor={address:{type:'object',required:true,fields:{street:{type:'string',required:true},city:{type:'string',required:true},zip:{type:'string',required:true,len:8,message:'invalid zip'},},},name:{type:'string',required:true},};constvalidator=newSchema(descriptor);validator.validate({address:{}},(errors,fields)=>{// errors for address.street, address.city, address.zip});

Note that if you do not specify therequired 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 theoptions passed to theschema.validate() method.

constdescriptor={address:{type:'object',required:true,options:{first:true},fields:{street:{type:'string',required:true},city:{type:'string',required:true},zip:{type:'string',required:true,len:8,message:'invalid zip'},},},name:{type:'string',required:true},};constvalidator=newSchema(descriptor);validator.validate({address:{}}).catch(({ errors, fields})=>{// now only errors for street and name});

The parent rule is also validated so if you have a set of rules such as:

constdescriptor={roles:{type:'array',required:true,len:3,fields:{0:{type:'string',required:true},1:{type:'string',required:true},2:{type:'string',required:true},},},};

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.

defaultField

ThedefaultField property can be used with thearray orobject type for validating all values of the container.It may be anobject orarray containing validation rules. For example:

constdescriptor={urls:{type:'array',required:true,defaultField:{type:'url'},},};

Note thatdefaultField is expanded tofields, seedeep rules.

Transform

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 atransform function to the validation rule. The property is transformed prior to validation and returned as promise result or callback result when pass validation.

importSchemafrom'async-validator';constdescriptor={name:{type:'string',required:true,pattern:/^[a-z]+$/,transform(value){returnvalue.trim();},},};constvalidator=newSchema(descriptor);constsource={name:' user  '};validator.validate(source).then((data)=>assert.equal(data.name,'user'));validator.validate(source,(errors,data)=>{assert.equal(data.name,'user'));});

Without thetransform 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.

Messages

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 amessage to a rule:

{name:{type:'string',required:true,message:'Name is required'}}

Message can be any type, such as jsx format.

{name:{type:'string',required:true,message:'<b>Name is required</b>'}}

Message can also be a function, e.g. if you use vue-i18n:

{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:

importSchemafrom'async-validator';constcn={required:'%s 必填',};constdescriptor={name:{type:'string',required:true}};constvalidator=newSchema(descriptor);// deep merge with defaultMessagesvalidator.messages(cn);...

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 theoptions.messages property within the validation function.

asyncValidator

You can customize the asynchronous validation function for the specified field:

constfields={asyncField:{asyncValidator(rule,value,callback){ajax({url:'xx',value:value,}).then(function(data){callback();},function(error){callback(newError(error));});},},promiseField:{asyncValidator(rule,value){returnajax({url:'xx',value:value,});},},};

validator

You can custom validate function for specified field:

constfields={field:{validator(rule,value,callback){returnvalue==='test';},message:'Value is not equal to "test".',},field2:{validator(rule,value,callback){returnnewError(`${value} is not equal to 'test'.`);},},arrField:{validator(rule,value){return[newError('Message 1'),newError('Message 2'),];},},};

FAQ

How to avoid global warning

importSchemafrom'async-validator';Schema.warning=function(){};

or

globalThis.ASYNC_VALIDATOR_NO_WARNING=1;

How to check if it istrue

Useenum type passingtrue as option.

{type:'enum',enum:[true],message:'',}

Test Case

npmtest

Coverage

npm run coverage

Open coverage/ dir

License

Everything isMIT.


[8]ページ先頭

©2009-2025 Movatter.jp