0

例如,我有 10 个输入。我想使用一个规则检查它们是否为空,但避免像这样重复:

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

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

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

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

1 回答 1

1

骨干验证文档

// 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;
    }
});
于 2016-12-02T22:23:05.657 回答