Backbone.Validation plugin - How to validate only the attributes that is set

1k Views Asked by At

How to validate just the one's that are set. Is there another method other than model.isValid(true) or model.validate() which would not validate the complete model. Here are some config that is there in my code

_.extend Backbone.Model.prototype, Backbone.Validation.mixin
Backbone.Validation.configure
        forceUpdate: true

setting one attribute with {validate:true} is triggering validate on the entire model

thanks

2

There are 2 best solutions below

0
On

There is preValidate method available, it only validates attributes passed to it.

Method description: https://github.com/thedersen/backbone.validation#prevalidate

0
On

model.isValid(true) validates all the fields of a model for which validations are defined, ignoring the fact if any filed is set or not.

For eg: Suppose you have a model having three fields viz. field1, field2, field3

var model = Backbone.Model.extend({
  validate: function(){
   //validation rules for field1, field2, field3
}
});

Now suppose you did model.isValid(true), it will validate all three fields no matter what. (passing true as argument do that). While if u do model.isValid() then it will only validate the fields that are set.

Now coming to your question, you are asking for something that could validate only the field you have set. For that u may use following:

var isValid = model.isValid('field1');