Search code examples
javascriptvalidationbackbone.jsbackbone.validation.js

One rule to validate several inputs with Backbone.validation


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!!!'
}

Solution

  • 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;
        }
    });