使用Backbone.validation验证多个输入的一条规则

时间:2016-11-28 13:11:50

标签: javascript validation backbone.js backbone.validation.js

我有10个输入。我想检查他们是否使用一条规则排空,但避免重复:

firstInput :{
    required: true,
    msg: 'Empty!'
},
// ...

tenthInput :{
    required: true,
    msg: 'Empty!'
}

是否有任何方法可以使用Backbone Validation对所有输入使用一条规则?并且每个输入可以同时具有其他唯一的验证规则,例如:

firstInput :{
    pattern: email,
    msg: 'Email!!!'
}

1 个答案:

答案 0 :(得分:1)

来自Backbone Validation documentation

// validation attribute can also be defined as a function returning a hash
var SomeModel = Backbone.Model.extend({
  validation: function() {
    return {
      name: {
        required: true
      }
    }
  }
});

然后,您可以调整模型以获得功能:

var SomeModel = Backbone.Model.extend({
    /**
     * List of field which are required.
     * @type {Array|Function}
     */
    required: ['firstInput', 'secondInput', /*...*/ 'tenthInput'],
    /**
     * Same format as Backbone Validation
     * @type {Object|Function}
     */
    specificValidation: {
        firstInput: {
            pattern: "email",
            msg: 'Email!!!'
        }
    },

    validation: function() {
        var inputs = _.result(this, 'required'),
            rules = _.result(this, 'specificValidation'),
            requiredRule = { required: true, msg: 'Empty!' };

        // apply the default validation to each listed field
        // only if not already defined.
        _.each(inputs, function(field) {
            rules[field] = _.defaults({}, rules[field], requiredRule);
        });

        return rules;
    }
});