async-validator 说明文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
异步验证
验证表单异步。https://github.com/freeformsystems/async-validate的变体
 
NPM版本 建立状态 测试范围 gemnasium deps 节点版本 npm下载
 
API
以下是从早期版本的async-validate中修改的。
 
用法
基本用法包括定义描述符,将其分配给模式,并将要验证的对象和回调函数传递给validate模式的方法:
 
var schema = require('async-validator');
var descriptor = {
  name: {
    type: "string",
    required: true,
    validator: (rule, value) => value === 'muji',
  },
};
var validator = new schema(descriptor);
validator.validate({name: "muji"}, (errors, fields) => {
  if(errors) {{name : “ muji ” },(errors,fields)=> {
   if(errors){
     //验证失败,错误是所有错误的数组
    //字段是由字段名称键入的对象,数组为
    /每个字段的/ errors
    return handleErrors(errors, fields);
  }
  //验证通过
});
 
// PROMISE USAGE
validator.validate({
  name: "muji",
  asyncValidator: (rule, value) => axios.post('/nameValidator', { name: value }),
}, (errors, fields) => {
  if(errors) {
     //验证失败,错误是所有错误的数组
    //字段是由字段名称键入的对象,
    每个字段返回//错误
     return handleErrors(errors, fields);
  }
  //验证通过
})
  .then(() => {
     //验证通过
  })
  catch(({errors,fields})=> {
     return  handleErrors(errors,fields);
  })
Validate
function(source,[ options ],callback):Promise
source:要验证的对象(必需)。
options:描述验证处理选项的对象(可选)。
callback:验证完成时调用的回调函数(必需)。
该方法将返回一个Promise对象,如:
 
then(),验证通过
catch({ errors, fields }),验证失败,错误是所有错误的数组,字段是由字段名称键入的对象,其数组为
Options
first:Boolean,callback当第一个验证规则生成错误时调用,不再处理验证规则。如果您的验证涉及多个异步调用(例如,数据库查询),并且您只需要第一个错误,请使用此选项。
 
firstFields:Boolean | String [],callback当指定字段的第一个验证规则生成错误时调用,不再处理相同字段的验证规则。 true意味着所有领域。
 
Rules
规则可以是执行验证的函数。
 
function(rule, value, callback, source, options)
rule:源描述符中与要验证的字段名称对应的验证规则。始终为其分配一个field属性,其中包含要验证的字段的名称。
value:要验证的源对象属性的值。
callback:完成验证后调用的回调函数。它期望传递一组Error实例来指示验证失败。如果检查是同步的,您可以直接返回false或Error或Error Array。
source:传递给validate方法的源对象。
options: 其他选项。
options.messages:包含验证错误消息的对象将与defaultMessages深度合并。
传递给validate或asyncValidate传递给验证函数的选项,以便您可以在验证函数中引用瞬态数据(例如模型引用)。但是,保留了一些选项名称; 如果使用选项对象的这些属性,则会覆盖它们。保留的属性是messages,exception和error。
 
var schema = require('async-validator');
var descriptor = {
  name(rule, value, callback, source, options) {
    var errors = [];
    if(!/^[a-z0-9]+$/.test(value)) {
      errors.push(
        new Error(
          util.format("%s must be lowercase alphanumeric characters",
            rule.field)));
    }
    return errors;
  }
}
var validator =  new  schema(descriptor);
validator.validate({name : “ Firstname ” },(errors,fields)=> {
   if(errors){
     return  handleErrors(errors,fields);
  }
  //验证通过
});
针对单个字段测试多个验证规则通常很有用,这样做可以使规则成为对象数组,例如:
 
var descriptor = {
  email: [
    {type: "string", required: true, pattern: schema.pattern.email},
    {validator(rule, value, callback, source, options) {
       var errors = [];
      //如果电子邮件地址已经存在于数据库测试
      //并添加验证错误,如果它的错误阵列
      return errors;
    }}
  ]
}
Type
指示type要使用的验证器。已识别的类型值为:
 
string:必须是类型string。This is the default type.
number:必须是类型number。
boolean:必须是类型boolean。
method:必须是类型function
regexp:必须是RegExp创建新项时不生成异常的实例或字符串RegExp。
integer:必须是类型number和整数。
float:必须是类型number和浮点数。
array:必须是由...确定的数组Array.isArray。
object:必须是类型object而不是Array.isArray。
enum:价值必须存在于enum
date:值必须有效,由确定 Date
url:必须是类型url。
hex:必须是类型hex。
email:必须是类型email。
Required
该required规则属性表示该字段必须存在于源对象被验证。
 
Pattern
该pattern规则属性指示一个正则表达式的值必须匹配,才能通过验证。
 
Range
使用min和max属性定义范围。对于string和array类型进行比较length,对于number类型,数量不得小于min或大于max。
 
Enumerable
要验证字段的确切长度,请指定该len属性。对于属性执行string和array类型比较length,对于number类型,此属性指示完全匹配number,即,它可能仅严格等于len。
 
如果len属性与min和max范围属性组合,len则优先。
 
枚举
要从可能值列表中验证值,请使用enum带有enum列出该字段有效值的属性的类型,例如:
 
var descriptor = {
   role: {type: "enum", enum: ['admin', 'user', 'guest']}
}
Whitespace
通常将仅包含空格的必填字段视为错误。要为仅包含空格的字符串添加其他测试,请将whitespace属性添加到值为的规则true。规则必须是一种string类型。
 
您可能希望清理用户输入而不是测试空格,请参阅transform以获取允许您去除空格的示例。
 
Deep Rules
 
如果您需要验证深对象属性可能对于那些的验证规则这样做object或者array通过向指定嵌套规则类型fields规则的属性。
 
var descriptor = {
  addres: {
    type : “ object ”,requried: true
    fieds: {
      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 }
}
var validator =  new  schema(descriptor);
validator.validate({address : {}},(errors,fields)=> {
   // address.street,address.city,address.zip的错误
});
请注意,如果未required在父规则上指定属性,则对于不在源对象上声明的字段完全有效,并且不会执行深度验证规则,因为没有任何要验证的内容。
 
深度规则验证为嵌套规则创建架构,因此您还可以指定options传递给schema.validate()方法。
 
var descriptor = {
  address: {
    type: "object", required: true, options: {single: true, 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}
}
var validator = new schema(descriptor);
 
validator.validate({ address: {} })
  .catch(({ errors, fields }) => {
     //现在只有街道和名称的错误    
  });
父规则也经过验证,因此如果您有一组规则,例如:
 
var 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"]}然后创建两个错误。一个用于数组长度不匹配,另一个用于索引2处缺少的所需数组条目。
 
defaultField
该defaultField属性可与arrayor或objecttype 一起使用,以验证容器的所有值。它可能是一个object或array包含验证规则。例如:
 
var descriptor = {
  urls: {
    type: "array", required: true,
    defaultField: {type: "url"}
  }
}
请注意,defaultField扩展为fields,请参阅深层规则。
 
Transform 转变
有时需要在验证之前转换值,可能是为了强制价值或以某种方式对其进行消毒。为此,请transform向验证规则添加一个函数。该属性在验证之前进行转换,并重新分配给源对象,以便在适当的位置改变属性的值。
 
var schema = require('async-validator');
var sanitize = require('validator').sanitize;
var descriptor = {
  name: {
    type: "string",
    required: true, pattern: /^[a-z]+$/,
    transform(value) {
      return sanitize(value).trim();
    }
  }
}
var validator = new schema(descriptor);
var source = {name: " user  "};
validator.validate(source)
  .then(() => assert.equal(source.name, "user"));;
如果没有transform函数验证,则由于模式不匹配而失败,因为输入包含前导和尾随空格,但是通过添加转换函数验证过程并且字段值同时被清理。
 
Messages
根据您的应用程序要求,您可能需要i18​​n支持,或者您可能更喜欢不同的验证错误消息。
 
实现此目的的最简单方法是为message规则分配:
 
{name : {type : “ string ”,required : true,message : “ Name is required ” }}
消息可以是任何类型,例如jsx格式。
 
{name : {type : “ string ”,required : true,message : < b >姓名是必需的< / b > }}
消息也可以是一个函数,例如,如果你使用vue-i18n:
 
{name : {type : “ string ”,required : true,message :()=>  this。$ t('名称是必需的')}}
您可能需要针对不同语言使用相同的架构验证规则,在这种情况下,复制每种语言的架构规则是没有意义的。
 
在这种情况下,您只需提供自己的语言消息并将其分配给架构:
 
var schema = require('async-validator');
var cn = {
  required: '%s 必填',
};
var descriptor = {name:{type: "string", required: true}};
var validator = new schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);
 
如果要定义自己的验证函数,最好将消息字符串分配给消息对象,然后通过options.messages验证函数中的属性访问消息。
 
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'),
      ];
    }
  },
};
常问问题
如何避免警告
var Schema = require('async-validator');
Schema.warning = function(){};
测试用例
npm test
npm run chrome-test
覆盖
npm run coverage
公开报道/目录
 
执照
一切都是麻省理工学院。
posted @   6NULL9  阅读(13492)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示