Validation groups for Backbone.Validation

356 Views Asked by At

I have a Backbone model, say User, and I want to reuse it in a Sign Up page and in a Change settings page.. In the Sign Up page I have a form with two fields: email and password both required, while in the Change Settings page there is another form with email and name (but not the password field), the first required the second one not..

Using the Backbone.Validation plugin I have something like this for the validation process:

var User = Backbone.Model.extend({

  validation: {
    name: {
      rangeLength: [0, 100]
    }
    email: {
      required: true
      pattern: "email"
      rangeLength: [1, 100]
    }
    password: {
      required: true
      rangeLength: [8, 100]
    }
  } // validation

} // User

It works well for the Sign Up form, but it doesn't work in the Change Settings form since the password is missing.

Is there a way for reusing the same validation on two different forms as in my case? Something like validation groups, one group for sign up's fields and another one for settings's field (where I could exclude the password)?..

1

There are 1 best solutions below

2
On

I have an idea if you're using the backbone.validator by thedersen v0.8.2 and above.
But it will pollute the model a little bit by introducing a flag attribute, which using to determine which kind of validation you need.

var User = Backbone.Model.extend({


  validation: function() {
      var validationCriteria = {
        name: {
          rangeLength: [0, 100]
        }
        email: {
          required: true
          pattern: "email"
          rangeLength: [1, 100]
        }
        password: {
          required: true
          rangeLength: [8, 100]
        }
      }

      switch (this.attributes.validationMode) {
        case 'signup':
          // do nothing since we need all validation. just to demonstare, if just two modes can just simple if statement
          break;
        case 'changeSetting':
          delete validationCriteria.password;
          break;
        default:
          break;
      }

      return validationCriteria; // validation

    } // User
});

var user = new User({
    validationMode: 'signup'
  }) //when initiate the model in signup view

var user = new User({
    validationMode: 'changeSetting'
  }) //when initiate the model in change setting view