Tag Archives: chaplin.js

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:

Screen Shot 2013-09-06 at 3.25.22 PM

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
  form: ->
    @view = new FormView region: 'main'
View = require 'views/base/view'
Form = require 'models/form'

module.exports = class FormView extends View
  autoRender: true
  className: 'form-view'
  template: require './templates/form'
    'click a.validateButton' : "validate"

  initialize: ->
    @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:

Screen Shot 2013-09-06 at 3.50.32 PM

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
  validation :
      required: true
      required: true
      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:

  attach: ->

Thats it! Full source code for the example is available on github.

Tagged , , ,
%d bloggers like this: