iview表单验证的简易封装

目前iview,ant-design等UI框架在表单处理方面都使用了async-validate来进行表单验证,并对其进行了封装以便更好的使用app

下面对最基本的使用作了简易封装
框架

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();
        }
    });
};
iview