文档:

安装

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.
email Must be of type email.
any Can be any type.