# async-validator
[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![node version][node-image]][node-url]
[![npm download][download-image]][download-url]
[![npm bundle size (minified + gzip)][bundlesize-image]][bundlesize-url]
[npm-image]: https://img.shields.io/npm/v/async-validator.svg?style=flat-square
[npm-url]: https://npmjs.org/package/async-validator
[travis-image]:https://app.travis-ci.com/yiminghe/async-validator.svg?branch=master
[travis-url]: https://app.travis-ci.com/github/yiminghe/async-validator
[coveralls-image]: https://img.shields.io/coveralls/yiminghe/async-validator.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/yiminghe/async-validator?branch=master
[node-image]: https://img.shields.io/badge/node.js-%3E=4.0.0-green.svg?style=flat-square
[node-url]: https://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/async-validator.svg?style=flat-square
[download-url]: https://npmjs.org/package/async-validator
[bundlesize-image]: https://img.shields.io/bundlephobia/minzip/async-validator.svg?label=gzip%20size
[bundlesize-url]: https://bundlephobia.com/result?p=async-validator
Validate form asynchronous. A variation of https://github.com/freeformsystems/async-validate
## Install
```bash
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 the `validate` method of the schema:
```js
import Schema from 'async-validator';
const descriptor = {
name: {
type: 'string',
required: true,
validator: (rule, value) => value === 'muji',
},
age: {
type: 'number',
asyncValidator: (rule, value) => {
return new Promise((resolve, reject) => {
if (value < 18) {
reject('too young'); // reject with error message
} else {
resolve();
}
});
},
},
};
const validator = new Schema(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 field
return handleErrors(errors, fields);
}
// validation passed
});
// PROMISE USAGE
validator.validate({ name: 'muji', age: 16 }).then(() => {
// validation passed or without error message
}).catch(({ errors, fields }) => {
return handleErrors(errors, fields);
});
```
## API
### Validate
```js
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, 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
Rules may be functions that perform validation.
```js
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 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`.
```js
import Schema from 'async-validator';
const descriptor = {
name(rule, value, callback, source, options) {
const errors = [];
if (!/^[a-z0-9]+$/.test(value)) {
errors.push(new Error(
util.format('%s must be lowercase alphanumeric characters', rule.field),
));
}
return errors;
},
};
const validator = new Schema(descriptor);
validator.validate({ name: 'Firstname' }, (errors, fields) => {
if (errors) {
return handleErrors(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:
```js
const descriptor = {
email: [
{ type: 'string', required: true, pattern: Schema.pattern.email },
{
validator(rule, value, callback, source, options) {
const errors = [];
// test if email address already exists in a database
// and add a validation error to the errors array if it does
return errors;
},
},
],
};
```
#### Type
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.
#### Required
The `required` rule property indicates that the field must exist on the source object being validated.
#### Pattern
The `pattern` rule property indicates a regular expression that the value must match to pass validation.
#### Range
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`.
#### Length
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.
#### Enumerable
> Since version 3.0.0 if you want to validate the values `0` or `false` inside `enum` 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:
```js
const descriptor = {
role: { type: 'enum', enum: ['admin', 'user
没有合适的资源?快使用搜索试试~ 我知道了~
开源头像挂件微信小程序-基于uniapp+vue3+skyline渲染框架.zip
共1055个文件
ts:451个
js:344个
svg:114个
需积分: 5 0 下载量 200 浏览量
2024-02-24
10:53:04
上传
评论
收藏 1.19MB ZIP 举报
温馨提示
【项目资源】: 包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。 包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】: 所有源码都经过严格测试,可以直接运行。 功能在确认正常工作后才上传。 【适用人群】: 适用于希望学习不同技术领域的小白或进阶学习者。 可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】: 项目具有较高的学习借鉴价值,也可直接拿来修改复刻。 对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】: 有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 鼓励下载和使用,并欢迎大家互相学习,共同进步。
资源推荐
资源详情
资源评论
收起资源包目录
开源头像挂件微信小程序-基于uniapp+vue3+skyline渲染框架.zip (1055个子文件)
CHANGELOG 48B
index.css 34KB
icon.css 6KB
.DS_Store 6KB
index.html 672B
qrcode.jpeg 49KB
mini-beebeered-2.jpg 255KB
vendor.js 216KB
index.js 12KB
index.js 12KB
index.js 9KB
index.js 9KB
index.js 9KB
index.js 8KB
index.js 8KB
popup.js 6KB
index.js 5KB
index.js 5KB
icon.js 5KB
index.js 4KB
index.js 4KB
cupertino-route.js 4KB
popup-custom.js 4KB
index.js 4KB
index.js 4KB
ru.js 3KB
icon-custom.js 3KB
sk.js 3KB
cs.js 3KB
sr-cyrl.js 3KB
uk.js 3KB
bn-bd.js 3KB
index.js 3KB
index.js 3KB
index.js 3KB
fi.js 3KB
index.js 2KB
sr.js 2KB
index.js 2KB
index.js 2KB
index.js 2KB
is.js 2KB
bn.js 2KB
app.js 2KB
bo.js 2KB
lt.js 2KB
scale-route.js 2KB
pl.js 2KB
scale-route.js 2KB
he.js 2KB
et.js 2KB
ku.js 2KB
index.js 2KB
br.js 2KB
hu.js 2KB
common.js 2KB
use-popup.js 2KB
ta.js 2KB
cupertino-route.js 2KB
ar.js 2KB
runtime.js 2KB
ml.js 2KB
popup-route.js 2KB
tzm.js 2KB
popup-route.js 2KB
ne.js 2KB
zh-cn.js 2KB
de-at.js 2KB
de.js 2KB
de-ch.js 2KB
popup-s-route.js 2KB
zh.js 2KB
popup-s-route.js 2KB
kn.js 2KB
opacity-route.js 2KB
zh-tw.js 2KB
index.js 2KB
index.js 2KB
gu.js 2KB
bg.js 2KB
te.js 2KB
pa-in.js 2KB
index.js 2KB
index.js 2KB
th.js 2KB
ka.js 2KB
my.js 2KB
utils.js 2KB
utils.js 2KB
dv.js 2KB
use-overlay.js 2KB
hi.js 2KB
hafl-screen-route.js 2KB
custom-route.js 2KB
index.js 2KB
index.js 2KB
lo.js 1KB
hr.js 1KB
km.js 1KB
hafl-screen-route.js 1KB
共 1055 条
- 1
- 2
- 3
- 4
- 5
- 6
- 11
资源评论
helloLinux!
- 粉丝: 168
- 资源: 76
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功