目前 iview,ant-design 等 UI 框架在表单处理方面都使用了 async-validate 来进行表单验证, 并对其进行了封装以便更好的使用
下面对最基本的使用做了简易封装
- module.exports = function(fields, source, success, fail) {
- var Schema = require("async-validate"),
- descriptor = {
- type: "object",
- fields: fields
- },
- schema = new Schema(descriptor),
- source = source;
- Schema.plugin([
- require("async-validate/plugin/object"),
- require("async-validate/plugin/string"),
- require("async-validate/plugin/util")
- ]);
- schema.validate(source, function(err, res) {
- if (err) {
- fail(err);
- // throw err; 对应于 callback(errInfo)
- } else if (res) {
- // validation failed, res.errors is an array of all errors
- // res.fields is a map keyed by field unique id (eg: `address.name`)
- // assigned an array of errors per field
- console.log("res");
- return console.dir(res.errors);
- // 对应于 raise()
- } else {
- success();
- }
- });
- };
来源: http://www.qdfuns.com/note/23231/0cd1b1a5b41562d9ba82ce47b578637d.html