当前位置:网站首页>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. |
边栏推荐
猜你喜欢
随机推荐
CANN媒体数据处理V2,JPEGD接口介绍
推荐两款超高质量的壁纸软件
Lumiprobe丨Lumizol RNA 提取试剂解决方案
Object tracking using tracker in opencv
数据资产为王,如何解析企业数字化转型与数据资产管理的关系?
NFT流动性协议的安全困局—NFT借贷协议XCarnival被黑事件分析
获取当前日期0点及23点59时间戳
Konva series tutorial 3: Customizing drawings
原生实现.NET5.0+ 自定义日志
Lumiprobe ProteOrange 蛋白质凝胶染料说明书
Chapter 2 processing files, cameras and GUI Cameo applications
EasyCVR新建用户后,视频调阅页面不能点击的问题修复
China gaobang brand story: standing guard for safety, gaobang pays attention to
About Critical Values
tensorboard 使用总结
从知名软件提取出的神器,吊打一众付费
使用.NetCore自带的后台作业,出入队简单模拟生产者消费者处理请求响应的数据
微软独家付费功能,也被完美解锁了
技术管理进阶——管理者如何做绩效沟通及把控风险
Introduction to apifox









