async-validator.js数据校验器

举报
彭世瑜 发表于 2022/06/29 00:41:55 2022/06/29
【摘要】 文档: https://www.npmjs.com/package/async-validatorhttps://github.com/yiminghe/async-validator 安装 npm...

文档:

安装

npm i async-validator

  
 
  • 1

示例

// 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);
  });



  
 
  • 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

打印出的校验信息

[
  { 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' } ]
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

rule的属性

type
required
pattern
len
enum
min/max

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以使用的 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.
email Must be of type email.
any Can be any type.

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/125496497

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。