Adding validateAll feature to Backbone.Model during set or save by gfranko · Pull Request #1595 · jashkenas/backbone

The _.extend call in question passes all of the model attributes to the validate method every time, regardless of the actual model attributes being set.

Let's look at a typical registration form use case that validates form fields using the blur event and validates each field regardless of whether other model attributes (aka other form data) are valid or not.

Example desired use case:

A user focuses and blurs first name, last name, and email HTML input boxes without entering any data. A "this field is required" message is presented next to each form field.

Here is a sample validate method that would be written using the current Backbone validate method:

validate: function(attrs) {

    if(!attrs.firstname) {
         console.log('first name is empty');
         return false;
    }

    if(!attrs.lastname) {
        console.log('last name is empty');
        return false;
    }

    if(!attrs.email) {
        console.log('email is empty');
        return false;
    }

}

This method would trigger a first name error each time any of the fields were blurred. This means that only an error message next to the first name field would be presented.

Here is a sample validate method that can be accomplished using my change.

validate: function(attrs) {

     if(attrs.firstname != null) {
         if(attrs.firstname.length === 0) {
             console.log('first name is empty');
             return false;
         }
     }

     if(attrs.lastname != null) {
         if(attrs.lastname.length === 0) {
             console.log('last name is empty');
             return false;
         }
     }

     if(attrs.email != null) {
         if(attrs.email.length === 0) {
             console.log('email is empty');
             return false;
         }
     }

}

This allows my logic inside of my validate method to determine which form fields are currently being set/validated, and does not care about the other model properties that are not trying to be set.