当前位置:网站首页>async-validator.js数据校验器
async-validator.js数据校验器
2022-06-28 18:35:00 【彭世瑜】
文档:
安装
npm i async-validator
示例
// demo.mjs
// node(v16.14.0)
// import Schema from 'async-validator';
// fix: 文档给出的引入方式报错
import asyncValidator from 'async-validator';
const Validator = asyncValidator.default;
// 定义校验规则
const rules = {
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 Validator(rules);
let data = {
name: 'Tom', age: 16 };
validator
.validate(data)
.then(() => {
// validation passed or without error message
console.log('validate passed');
})
.catch(({
errors, fields }) => {
console.log(errors, fields);
});
打印出的校验信息
[
{
message: 'name fails', fieldValue: 'Tom', field: 'name' },
{
message: 'too young', fieldValue: 16, field: 'age' }
] {
name: [ {
message: 'name fails', fieldValue: 'Tom', field: 'name' } ],
age: [ {
message: 'too young', fieldValue: 16, field: 'age' } ]
}
rule的属性
type
required
pattern
len
enum
min/max
可以使用的 Type
| 类型 | 描述 |
|---|---|
| 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. |
| Must be of type email. | |
| any | Can be any type. |
边栏推荐
- Advanced technology management - how managers communicate performance and control risks
- Learning notes: how to time 10ms for 51 single chip microcomputer (STC89C52)
- 第2章 处理文件、摄像头和图形用户界面cameo应用
- 电子商务盛行,怎么提高商店转换率?
- leetcode 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers(最少的“二进制数“个数)
- Chapter 2 processing files, cameras and GUI Cameo applications
- 向上转型和向下转型
- 声网发布灵隼物联网云平台 可一小时构建示例场景
- Win 10创建一个gin框架的项目
- 微软独家付费功能,也被完美解锁了
猜你喜欢
随机推荐
记一次Emotet木马处理案例
技术管理进阶——管理者如何做绩效沟通及把控风险
Graphic system - 2 View drawing
Lumiprobe 蛋白质标记研究方案
use. NETCORE's own background job, which simply simulates producers and consumers' processing of request response data in and out of the queue
Steam education to break the barriers between disciplines
CANN媒体数据处理V2,JPEGD接口介绍
原生实现.NET5.0+ 自定义日志
内存抖动
POI Excel转换工具
618活动季——百数低代码平台特享折扣来临
图形系统——1. 布局加载
推荐两款超高质量的壁纸软件
模块化操作
C语言文件操作
Introduction to apifox
Lumiprobe ProteOrange 蛋白质凝胶染料说明书
MindSpore系列一加载图像分类数据集
微软独家付费功能,也被完美解锁了
百度时间因子添加









