2

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)?..

Andrea
  • 15,900
  • 18
  • 65
  • 84

1 Answers1

0

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
ChinKang
  • 4,212
  • 2
  • 17
  • 29
  • Thanks for your idea.. Yes, I'm using the plugin by thedersen.. I don't understand how to use your code.. Can I use the method `this.model.isValid(true)` from a view?.. Where I could specify the validationMode? – Andrea Jan 08 '15 at 20:27
  • yes u can use all the original feature. depending on you are using the model in which view(either signup or changeSetting view) to set the validationMode(a custom attribute added, can be any name) – ChinKang Jan 09 '15 at 00:38