Model Validation in Backbone.js With jQuery

Introduction

This article explains Model Validation in Backbone with jQuery. Here we will create a simple form and use validation when the form information is filled in that displays the validation message.

 Here we use the following three scripts files:

    <script src='http://code.jquery.com/jquery.js'></script>

    <script src='http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.1.1/lodash.min.js'></script>

    <script src='http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js'></script>

We will now create the sample application showing the use of validation.

Step 1

Create a Web application as in the following:

  • Start Visual Studio 2013. From the Start window select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and select "Empty Web Application".

Select Empty Web Application

  • Click on the "OK" button.

Step 2

Now add the HTML page.

  • In the Solution Explorer.
  • Right-click on the project then select "Add" -> "HTML page".

Add HTML Page

  • Change the name of the page.
Change Name
  • Click on the "Add" button.

Add the following code:

<!doctype html>

<html>

<head>

    <meta charset=utf-8>

    <title>Form validation using backbone jquery</title>

    <script src='http://code.jquery.com/jquery.js'></script>

    <script src='http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.1.1/lodash.min.js'></script>

    <script src='http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js'></script>

    <script>

    jQuery(function($) {

        //Backbone Model and Validation Method

       var Client = Backbone.Model.extend({

          // RegEx Patterns

          // ==============

          patterns: {

              specialCharacters: "[^a-zA-Z 0-9]+",

              digits: "[0-9]",

              email: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]*[.]{1}[a-zA-Z]{2,6}$",

              phone: "^([0-9]{3})?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"

          },

          // Validators

          // ==========

          validators: {

              minLength: function(value, minLength) {

                  return value.length >= minLength;

              },

              maxLength: function(value, maxLength) {

                  return value.length <= maxLength;

              },

              pattern: function(value, pattern) {

                  return new RegExp(pattern, "gi").test(value) ? true : false;

              },

              isEmail: function(value) {

                  return Client.prototype.validators.pattern(value, Client.prototype.patterns.email);

              },

              isPhone: function(value) {

                  return Client.prototype.validators.pattern(value, Client.prototype.patterns.phone);

              },

              hasSpecialCharacter: function(value) {

                  return Client.prototype.validators.pattern(value, Client.prototype.patterns.specialCharacters);

              },

              hasDigit: function(value) {

                  return Client.prototype.validators.pattern(value, Client.prototype.patterns.digits);

              }

          },

          validate: function(attribute) {

              console.log('attribute', attribute);

              var errors = this.errors = {};

              if (attribute.fname != null) {

                  if (!attribute.fname) errors.fname = 'First Name of Person is Required';

                  else if (!this.validators.minLength(attribute.fname, 2)) errors.fname = 'Length of First Name is too Short';

                  else if (!this.validators.maxLength(attribute.fname, 15)) errors.firstname = 'Length of First Name is too large';

                  else if (this.validators.hasSpecialCharacter(attribute.fname)) errors.fname = 'It does not contain special characters';

              }

              if (attribute.lname != null) {

                  if (!attribute.lname) errors.lname = 'Last Name of Person is Required';

                  else if (!this.validators.minLength(attribute.lname, 2)) errors.lname = 'Length of Last Name is too Short';

                  else if (!this.validators.maxLength(attribute.lname, 15)) errors.lname = 'Length of Last Name is too Large';

                  else if (this.validators.hasSpecialCharacter(attribute.lname)) errors.lname = 'It does not contain special characters';

              }

              if (attribute.password != null) {

                  if (!attribute.password) errors.password = 'Required Password';

                  else if (!this.validators.minLength(attribute.password, 6)) errors.password = 'Length of Password is too short';

                  else if (!this.validators.maxLength(attribute.password, 15)) errors.password = 'Length of Password is too Large';

                  else if (!this.validators.hasSpecialCharacter(attribute.password)) errors.password = 'password must contain a special character';

                  else if (!this.validators.hasDigit(attribute.password)) errors.password = 'password must contain a digit';

              }

              if (attribute.email != null) {

                  if (!attribute.email) errors.email = 'Email is required';

                  else if (!this.validators.isEmail(attribute.email)) errors.email = 'Mail Format is not valid';

              }

              if (attribute.phone != null) {

                  if (!attribute.phone) errors.phone = 'Phone Number is required';

                  else if (!this.validators.isPhone(attribute.phone)) errors.phone = 'Invlaid Phone Number';

              }

              if (!_.isEmpty(errors)) {

                return errors;

              }

          }

      });

      var Record = Backbone.View.extend({

        events: {blur: 'validate'},

        initialize: function() {

          this.name = this.$el.attr('name');

          this.$msg = $('[data-msg=' + this.name + ']');

        },

        validate: function() {

          var self = this,

            obj = {};

          obj[this.name] = this.$el.val();

          this.model.set(obj, {validate: true, validateAll: false}, { error: function(model, obj) {

            console.log(obj);

          }}

          );

          this.$msg.text(this.model.errors[this.name] || '');

        }

      });

        //Create the Model Instance

      var client = new Client;

      $('input').each(function() {

        new Record({el: this, model: client});

      });

    });

    </script>

</head>

<!--create an HTML Form-->

<body>

    <form>

        <label>First Name</label>

        <input type="text" name='fname'>

        <span data-msg='fname'></span>

        <br>

        <label>Last Name</label>

        <input type="text" name='lname'>

        <span data-msg='lname'></span>

        <br>

        <label>Password</label>

        <input type="password" name='password'>

        <span data-msg='password'></span>

        <br>

        <label>Email</label>

        <input type="text" name='email'>

        <span data-msg='email'></span>

        <br>

        <label>Phone</label>

        <input type="text" name='phone'>

        <span data-msg='phone'></span>

    </form>

</body>

</html>

Step 3

Execute the application:

Form display

Provide something in the text boxes. It will then display the validation message as in the following:

Display Validation message

Up Next
    Ebook Download
    View all
    Learn
    View all