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'
  events: 
    'click a.validateButton' : "validate"

  initialize: ->
    super
    @model = new Form()

  validate: (e) ->
    @model.validate()
    e.preventDefault()

<form>
  <div>
    <label for="name">Name</label><input type="text" name="name" class="name" />
  </div>
  <div>
    <label for="phone">Phone</label><input type="text" name="phone" class="phone" />
  </div>
  <div>
    <label for="email">Email</label><input type="text" name="email" class="email" />
  </div>
  <a href="#" class="validateButton">Validate</a>
</form>

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 :
    name:
      required: true
    email:
      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: ->
    super
    Backbone.Validation.bind(@);

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

Tagged , , ,
%d bloggers like this: