0

I have 10 inputs for instance. And I want to check if they're empty using one rule but avoiding reiteration like this:

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

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

Is there any method to use one rule for all inputs using Backbone Validation? And each input can have other unique validation rules the same time, e.g.:

firstInput :{
    pattern: email,
    msg: 'Email!!!'
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
nllsdfx
  • 900
  • 14
  • 30

1 Answers1

1

From the 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
      }
    }
  }
});

You could then adjust your model to have a function:

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;
    }
});
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • what's about bindings to a view? I did your example but `Uncaught TypeError: Cannot read property 'call' of undefined` appears – nllsdfx Dec 22 '16 at 13:30
  • @DmitrySoroka it should work out of the box, but maybe I forgot something or maybe you're using something that I don't know, so the bug is possibly elsewhere. It'd be best you ask a new question with a [mcve]. – Emile Bergeron Dec 22 '16 at 16:44
  • I figured it out! A key of a `specificValidation` can be array of objects with rules. But your `rules[field] = _.defaults({}, rules[field], requiredRule)` handles only objects, not arrays of objects. – nllsdfx Dec 28 '16 at 12:34
  • @DmitrySoroka `specificValidation` and `required` fields are custom for this situation, `specificValidation` key **can't** have an array as it is. It meant to be merged and override the `required` field if necessary. So it can't really handle multiple `msg` right. – Emile Bergeron Dec 28 '16 at 17:20