文档:
安装
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