Rules
Rules may be functions that perform validation.
function(rule, value, callback, source, options)
rule
: Object
{
"field": "name", // 检查的属性的名
"fullField": "name", //
"type": "string", // 类型默认 string
"validator": "ƒ" // 检查的函数
}
value
: 用户输入的值callback
:验证完成后调用的回调函数。它期望传递一个’ Error ‘实例数组来指示验证失败。如果检查是同步的,则可以直接返回’ false ‘或’ Error ‘或’ Error Array '。source
: 传递给“validate”方法的源对象。options
:额外选项,.
{
"firstFields": true,
"messages": {
"default": "Validation error on field %s",
"required": "%s is required",
"enum": "%s must be one of %s",
"whitespace": "%s cannot be empty",
"date": {
"format": "%s date %s is invalid for format %s",
"parse": "%s date could not be parsed, %s is invalid ",
"invalid": "%s date %s is invalid"
},
"types": {
"string": "%s is not a %s",
"method": "%s is not a %s (function)",
"array": "%s is not an %s",
"object": "%s is not an %s",
"number": "%s is not a %s",
"date": "%s is not a %s",
"boolean": "%s is not a %s",
"integer": "%s is not an %s",
"float": "%s is not a %s",
"regexp": "%s is not a valid %s",
"email": "%s is not a valid %s",
"url": "%s is not a valid %s",
"hex": "%s is not a valid %s"
},
"string": {
"len": "%s must be exactly %s characters",
"min": "%s must be at least %s characters",
"max": "%s cannot be longer than %s characters",
"range": "%s must be between %s and %s characters"
},
"number": {
"len": "%s must equal %s",
"min": "%s cannot be less than %s",
"max": "%s cannot be greater than %s",
"range": "%s must be between %s and %s"
},
"array": {
"len": "%s must be exactly %s in length",
"min": "%s cannot be less than %s in length",
"max": "%s cannot be greater than %s in length",
"range": "%s must be between %s and %s in length"
},
"pattern": {
"mismatch": "%s value %s does not match pattern %s"
}
}
}
Type
Indicates the type
of validator to use. Recognised type values are:
-
string
: 字符串string
.默认类型.
-
number
: 数字. -
boolean
:布尔. -
method
: 方法. -
regexp
:正则 -
integer
:是数字并且是整型. -
float
: 是数字并且是浮点型. -
array
: 数组. -
object
:对象. -
enum
: 规定类型,[‘red’,‘blue’,‘black’]. -
date
: 时间 -
url
:url
. -
hex
: 16进制. -
email
: 邮件. -
any
:不控制.
Required
是否必填
Pattern
自定义校验规则正则表达式
Range
区间控制
min
:最小
max
:最大
Length
len
:长度
Enumerable
要从可能的值列表中验证一个值,使用’ enum ‘类型和’ enum '属性列出该字段的有效值,例如:
const descriptor = {
role: { type: 'enum', enum: ['admin', 'user', 'guest'] },
};
Whitespace
全字段通常将只包含空格的必填项视为错误。要对仅由空格组成的字符串添加额外的测试,请给规则添加一个值为true
的whitespace
属性。规则必须是string
类型。
Deep Rules
验证深层对象属性,你可以通过将嵌套规则分配给规则的’ fields ‘属性来验证’ object ‘或’ array '类型的验证规则。
const descriptor = {
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 },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} }, (errors, fields) => {
// errors for address.street, address.city, address.zip
});
注意,如果你没有在父规则上指定“required”属性,那么在源对象上声明的字段是完全有效的,并且深度验证规则将不会被执行,因为没有任何东西可以验证。
深度规则验证为嵌套规则创建一个模式,所以你也可以指定传递给’ schema.validate() ‘方法的’ options '。
const descriptor = {
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 },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} })
.catch(({ errors, fields }) => {
// now only errors for street and name
});
父规则也会被验证,所以如果你有一组规则,比如:
const descriptor = {
roles: {
type: 'array',
required: true,
len: 3,
fields: {
0: { type: 'string', required: true },
1: { type: 'string', required: true },
2: { type: 'string', required: true },
},
},
};
并提供一个源对象 { roles: ['admin', 'user'] }
此时会有两个判断.一个是数组长度,一个数数组中的值判断
defaultField
’ defaultField ‘属性可以与’ array ‘或’ object '类型一起使用,用于验证容器的所有值。
它可以是包含验证规则的“对象”或“数组”。例如:
const descriptor = {
urls: {
type: 'array',
required: true,
defaultField: { type: 'url' },
},
};
Transform
如果需要在验证之前转换值。使用这个规则.。这个方法在验证之前运行
import Schema from 'async-validator';
const descriptor = {
name: {
type: 'string',
required: true,
pattern: /^[a-z]+$/,
transform(value) {
return value.trim();
},
},
};
const validator = new Schema(descriptor);
const source = { name: ' user ' };
validator.validate(source)
.then((data) => assert.equal(data.name, 'user'));
validator.validate(source,(errors, data)=>{
assert.equal(data.name, 'user'));
});
Messages
报错信息
{ name: { type: 'string', required: true, message: 'Name is required' } }
{ name: { type: 'string', required: true, message: '<b>Name is required</b>' } }
{ name: { type: 'string', required: true, message: () => this.$t( 'name is required' ) } }
如果需要对不同的语言使用相同的模式验证规则,在这种情况下,为每种语言复制模式规则是没有意义的。
在这种情况下,你可以为语言提供你自己的消息,并将其分配给模式:
import Schema from 'async-validator';
const cn = {
required: '%s 必填',
};
const descriptor = { name: { type: 'string', required: true } };
const validator = new Schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);
...
定义自己的验证函数,最好的做法是将消息字符串分配给消息对象,然后通过’ options '访问消息。消息属性在验证函数中。
asyncValidator
指定的字段自定义异步验证功能:
const fields = {
asyncField: {
asyncValidator(rule, value, callback) {
ajax({
url: 'xx',
value: value,
}).then(function(data) {
callback();
}, function(error) {
callback(new Error(error));
});
},
},
promiseField: {
asyncValidator(rule, value) {
return ajax({
url: 'xx',
value: value,
});
},
},
};
validator
您可以为指定字段自定义验证函数:
const fields = {
field: {
validator(rule, value, callback) {
return value === 'test';
},
message: 'Value is not equal to "test".',
},
field2: {
validator(rule, value, callback) {
return new Error(`${value} is not equal to 'test'.`);
},
},
arrField: {
validator(rule, value) {
return [
new Error('Message 1'),
new Error('Message 2'),
];
},
},
};