In my previous blog, I discussed about Spine model binding and events. If you do not have idea on Spine Model binding, I would like to suggest you to go through my previous blog as I am using the similar binding here.

Introduction:

In real world, it’s quite often to make mistakes, and here, there is always a chance to enter wrong/ invalid details in the input controls. It’s developer’s responsibility to inform the user what is wrong in the input with proper error messages. It’s always better to do the validations at the client side rather than server side. This avoids extra round trip (request + response) to the server to validate the basic rules against user input data.

There is no straight forward way/ algorithm to do the client side script validations. Here is the simple model validation framework for Spine. This allows you to mix strong validation rules with fluid English context.

Install:

Download spine.js, spine.databind.js, spine.validate.js and include it in your html.

<script src=”Scripts/spine.js” type=”text/javascript”></script><scriptsrc=”Scripts/spine.databind.js”type=”text/javascript”></script>
<script src=”Scripts/spine.validate.js” type=”text/javascript”></script>

You can download the above script files from here and here or download validations sample app attached with this article. It has these files with small example.

How to Use:

Set up a Spine Model.

 var PersonModel = Spine.Model.setup(“Person”, [“firstName”, “lastName”, “DOB”, “Age”, “State”, “Zip”, “Email”]);

Add the validation object to Model.

PersonModel.include(Spine.Validate);

Setup some simple (but strong) rules to the model as follows.

PersonModel.include({
rules: function (RuleFor) {
   return [
      RuleFor(“firstName”)
          .Required(),
      RuleFor(“lastName”)
          .Matches(/^[a-zA-Z ]*$/)
          .Message(“Last Name should contain only alphabets”),
      RuleFor(“DOB”)
          .IsDate()
          .IsInPast(),
      RuleFor(“Age”)
          .ItShouldBe()
          .Between(18, 25),
      RuleFor(“State”)
          .Required()
          .When(function (record) {
                        return record.Zip !== undefined && record.Zip.length > 0
          })
          .MaxLength(2)
          .Message(“State Code must be less than 3 characters”),
      RuleFor(“Zip”)
          .WhenNotBlank()
          .IsNumeric()
          .Length(6)
          .Message(“Zip code should contain 6 in length”),
      RuleFor(“Email”)
          .EmailAddress()
          .Message(“Incorrect Email format”)
]
}
});

Setup a controller with bindings, model binding initialization method and validation methods.

var PersonController = Spine.Controller.create({

bindings:
{
          “value [name=firstName]”          :           “firstName”,
          “value [name=lastName]”           :           “lastName”,
          “value [name=DOB]”                      :           “DOB”,
          “value [name=Age]”                       :           “Age”,
          “value [name=State]”                     :           “State”,
          “value [name=Zip]”                         :           “Zip”,
          “value [name=Email]”                    :           “Email”
},
init: function () {
          this.refreshBindings(this.model);
          this.model.bind(“error”, this.error);
          this.model.bind(“update”, this.clear);
},
clear: function () {
          Controller.el.find(‘.errorDiv’).remove();
          Controller.el.find(‘.fail’).removeClass(‘fail’);
},
error: function (item, errors) {
          Controller.clear();
          var list = [];
          for (var i in errors) {
                    var error = errors[i];
                    var element = Controller.el.find(‘input[name=’ + error.property + ‘]’)
                    if (element != null && element != undefined) {
                    element.addClass(‘fail’);
                    var spanHTML = ‘<small class=”errorDiv”>’ + error.message +
                          ‘</small>’
;
                    $(element).after(spanHTML);
          }
          list.push(error.message);
}

}
});

After that whenever spine would normally call your custom “validate” method it will run through all the rules and send out error events just like you are used to.

This validation mechanism is different for different applications. I have collected all the errors whenever model error occurs and attached error messages to each invalid input control. You can update as per your requirement.

Include spine.databind object, define model with values, initialize controller.

PersonController.include(Spine.DataBind);

var Person = PersonModel.create({ id: 4, firstName: “Pramati”, lastName: “Technologies”, DOB: “12-12-2012”, Age: “22”, State: “AP”, Zip: “500034”, Email: “validations@spine.com” });

var Controller = PersonController.init({ el: ‘body’, model: Person });

And, here is the view which will be in the UI

<table cellpadding=”6″ cellspacing=”6″>
   <tbody>
      <tr>
         <td>First Name:</td>
         <td><input type=”text” name=”firstName” />*</td>
      </tr>
      <tr>
         <td>Last Name:</td>
         <td><input type=”text” name=”lastName” /></td>
      </tr>
      <tr>
         <td>DOB:</td>
         <td><input type=”text” name=”DOB” /></td>
      </tr>
      <tr>
         <td>Age:</td>
         <td><input type=”text” name=”Age” /></td>
      </tr>
      <tr>
         <td>State:</td>
         <td><input type=”text” name=”State” /></td>
      </tr>
      <tr>
         <td>Zip:</td>
         <td><input type=”text” name=”Zip” /></td>
      </tr>
      <tr>
         <td>Email:</td>
         <td><input type=”text” name=”Email” /></td>
      </tr>
   </tbody>
</table>

Conclusion:

Spine.validate.js provides an excellent and simple way to handle the Spine model validations. You can use the validation methods just like how you write the name of the validation in English (require(), ItMustBe() GreaterThan(10), IsDate(), NotNull() etc.) If you can go through the spine.validate.js code, you can easily understand the way how the validations handled. You can extend it by adding methods as per your validation logic.

References:

http://spinejs.com/docs/forms
https://github.com/nathanpalmer/spine.validate

 

Sample App:

You can download the above sample working code (with ASP.NET web application) from here.