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
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 eitherset
orsave
.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:
And you can get this error message whenever you need it