Client side validation with Backbone.js
Happy 2014 everyone! May the new year bring you great happiness and lots of programming fun. I myself had an eventful 2013 and really hope that 2014 is less dramatic and more relaxing, now that I am in a great city and a very nice country (which was my dream for a long time).
Back to technology, client side validation is a nice little feature that improves the user’s experience and saves some valuable bandwidth. To kick things off in the new year we will look at how we can use Backbone.js to add some simple client side validation.
For our experiment, the code for which is available on github we have a simple user registration form. We want to ensure that the -
- user has entered a valid email
- the password is atleast 6 characters long and
- the password confirmation matches the password entered earlier.
Backbone out of the box does provide us two methods that we can use for validation (validate and isValid). Let us see the code of the form’s Backbone view -
And the model itself -
Basically, all we needed to do was to override the validate method of the model and check if the model is valid before submitting the form. If the model is invalid, an “invalid” event is triggered which we can listen to and take desired action.
This is reasonably good but can we do better, I guess two things that can be improved are -
- Make the validations more declarative, not the if/else/unless mess.
- Use more reusable validations like Rails.
Luckily, there is a Backbone plugin that can help us - Backbone Validation. Let’s see how the code looks after using this plugin.
And now the model has its validations declared as config -
This is a bit better, we have a set of reusable / built-in validations and we have avoided the if/then/unless mess. So that is all folks, have a great year ahead.