Backbone.Validation with Chaplin and CoffeeScript
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.
1 module.exports = (match) ->
2 match '', 'home#index'
3 match 'form', 'home#form'
1 Controller = require 'controllers/base/controller'
2 HeaderView = require 'views/home/header-view'
3 FormView = require 'views/home/form'p>
4 module.exports = class HomeController extends Controller
5 form: ->
6 @view = new FormView region: 'main'
1 View = require 'views/base/view'
2 Form = require 'models/form'
3 module.exports = class FormView extends View
4 autoRender: true
5 className: 'form-view'
6 template: require './templates/form'
7 events:
8 'click a.validateButton' : "validate"
9 initialize: ->
10 super
11 @model = new Form()
12 validate: (e) ->
13 @model.validate()
14 e.preventDefault()
1
2
3 type="text" name="name" class="name" />
4
5
6 type="text" name="phone" class="phone" />
7
8
9 type="text" name="email" class="email" />
10
11 href="#" class="validateButton">Validate
12
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.
1 BaseModel = require 'models/base/model'
2 module.exports = class Form extends BaseModel
3 validation :
4 name:
5 required: true
6 email:
7 required: true
8 pattern: "email"
We’ll also need to add the code to our vendor/scripts folder.
In a perfect world, the @model.validate() call would execute our validation rules. However, in this world, we get a javascript error
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:
1 attach: ->
2 super
3 Backbone.Validation.bind(@);
Thats it! Full source code for the example is available on github.