Backbone Validations on multiple fields of a model and returning same error

736 Views Asked by At

I have a model which has three fields field1, field2, field3. I have to validate that if any one of the three fields has some value then no error should be returned else an error should be returned.

My research: I can use Backbone.Validations plugin for this. as follows :

var model = Backbone.Model.extend({
  validation: {
    field1: {
        required: true,
        msg : "Field is required"
    }
    ,field2: {
        required: true,
        msg : "Field is required"
    }
    ,field3: {
        required: true,
        msg : "Field is required"
    }
  }
});

The above code will validate all three fields to be required.

I am clear until here. What i want is that if field1 is null, only then field2 is validated and similarly if field2 is null only then field3 is validated. And if field3 is also null, then an error message is returned. As soon as any of three fields is found to have a value the subsequent fields should not be validated.

I am not sure , if it possible to do such conditional validations using Backbone.Validations plugin. Please help, if this is possible. Also please suggest any links i may use to study Backbone more deeply as i am just a newbie to it.

I am following the following link for Backbone.Validation : https://github.com/thedersen/backbone.validation

1

There are 1 best solutions below

1
On

Never used Backbone.Validation but you could roll your own validation, it's pretty simple with Backbone.

http://backbonejs.org/#Model-validate

Just define a validate method on your Model. It will receive as arguments the current model attributes, as well as the options passed to either set or save.

var MyModel = Backbone.Model.extend({
  validate: function(attrs, options){
    if(_.isUndefined(attrs.field1) && _.isUndefined(attrs.fields2) && _.isUndefined(attrs.field3)){
      //return your error as you wish
      return { message: "Either field1, field2 or field3 must be present" }
    }          
  }
});

Note that Backbone documentation states that in the validate method, don't return anything if everything was fine.

You can then test the validation whenever you want with:

var model = new MyModel();
console.log(model.isValid());

And you can get this error message whenever you need it

console.log(model.validationError.message);