Ember-Validatable

Over the last week or so we’ve been experimenting with Ember-Model as a possible replacement for Ember-Data which has been causing us a few headaches recently (which is fair enough, it is alpha software).

One of the things we need from whichever persistence mechanism we use is client-side validations. Of course, you still have to validate your incoming data on the server, but doing it on the client-side allows a good UI to be built around the editing process, without having to wait for the data be sent to the server and back.

We decided to add (very simple) validation support to Ember-Model, and spent a few hours whipping something up as a proof-of-concept pull request, however Erik thinks that validations are outside the scope of Ember-Model (and upon some reflection we agree with him). I’ve split it off into a small package called Ember-Validatable.

Ember-Validatable allows you to easily add validations to any object using the Ember.Validatable mixin. Once you have mixed in EV you can add a special fooValidation or fooValidations property which to which you can pass a subclass of Ember.Validator:

1
2
3
4
5
6
7
8
9
10
11
12
var TimeTravelValidation = Ember.Validator.extend({
  message: 'must be at least 88mph',

  isValid: function() {
    return parseInt(this.get('content')) >= 88;
  }.property('content')
});

App.TimeTravel = Ember.Object.extend(Ember.Validatable, {
  speed: '17mph',
  speedValidation: TimeTravelValidation
})

This will set an instance of App.TimeTravel’s isValid property to false and add an error message to it’s errors property. These will be cleared as soon as the speed property is set to something greater than or equal to 88.

There is more thorough documentation in the readme should you need it.

EV is brand new, so please send bug reports and pull requests on the GitHubs if you have problems or suggestions.

Comments