Any sizable web application needs validation. Doing it yourself is for the birds, so I wanted to incorporate a backbone plugin to help solve the problem. For this example I chose to use Backbone.Validation.
Start with a basic framework. Brunch Application Assembler is a great way to bootstrap these projects. I used Paul Miller’s brunch-with-chaplin skeleton.
brunch new gh:paulmillr/brunch-with-chaplin
To start up the server, type brunch watch –server and go to http://localhost:3333/ in a new browser window. If everything is good, you’ll see this:
You’ll need a basic application to test out our concept, so we’ll modify the routes and the controller, and add a new view and template to our project.
module.exports = (match) ->
match '', 'home#index'
match 'form', 'home#form'
Controller = require 'controllers/base/controller'
HeaderView = require 'views/home/header-view'
FormView = require 'views/home/form'
module.exports = class HomeController extends Controller
@view = new FormView region: 'main'
View = require 'views/base/view'
Form = require 'models/form'
module.exports = class FormView extends View
template: require './templates/form'
'click a.validateButton' : "validate"
@model = new Form()
validate: (e) ->
<label for="name">Name</label><input type="text" name="name" class="name" />
<label for="phone">Phone</label><input type="text" name="phone" class="phone" />
<label for="email">Email</label><input type="text" name="email" class="email" />
<a href="#" class="validateButton">Validate</a>
With that code in place, lets do a quick checkpoint http://localhost:3333/form. We should get an ugly view like this:
So, we know we want a basic form that can save name, phone, and email. Following the guidelines on the validation docs https://github.com/thedersen/backbone.validation, lets add the rules to our model.
BaseModel = require 'models/base/model'
module.exports = class Form extends BaseModel
We’ll also need to add the code to our vendor/scripts folder.
Uncaught TypeError: Object # has no method ‘validate’
There is one final step. We need to bind our model to the validation, so add the call in the attach method of our view:
Thats it! Full source code for the example is available on github.