Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

Validating the data


In Backbone, validation is taken care of by the model.validate() method. By default, the Backbone.Model class doesn't have a validate() method on its own. However, the developers are encouraged to add a validate() method that gets called by the model every time an attribute is saved or set with validate: true passed. A copy of the attributes is sent to the validate() method with all the changed values. Let's look at a simple data validation:

var User = Backbone.Model.extend({
  validation: {    emailRegEx: /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/
},

  defaults: {
    name: '',
    email: ''
  },

  validate: function (attr) {
    if (attr.name.length === 0) {
      return 'Name is required';
    }

    if (attr.email.length === 0) {
      return 'Email is required';
    }

    if (!this.validation.emailRegEx.test(attr.email)) {
      return 'Please provide a valid email';
    }
  }
});

// Define the user view
var UserView = Backbone...