Tag: emberdata


Models, as the name presumes, do ‘model’ data; they sort of outline data, from which content can be created. With that in mind, it’s not unlikely you want to validate created content every once and a while. Notify that given content is or isn’t the way the model intended the data to be.

The approach in this article is adding validation functionality (call it tools) to a model, before modelling. When a developer ‘models a model’ he can tell what each field should or shouldn’t accept for given content.
It’s a REALLY SIMPLE approach, there are other more complex, perhaps more ’emberish’, solutions out there. But this has you up and running quickly, and has useful functionality for templates and can thus be used in combination with input elements, especially when you have your input bound with model-fields, such as {{ input type=”text” value=model.employeeName }}.

Download the file here

It’s on GitHub Gist now 🙂

I’m assuming you’re using Ember-CLI.
You can follow the extended instruction in the file-comment, but I’ll briefly show you what it’s about, so you get an idea whether this suits your project or not:

Put the file in you model directory (or somewhere more appropriate), and import it to your desired model, say a Person model:


import DS from 'ember-data';
import Validation from 'your-app/models/validation';

export default Validation.extend({
    firstName :  DS.attr('string'),  // required
    lastName :   DS.attr('string'),  // required
    age :        DS.attr('integer'), // numeric
    town :       DS.attr('string'),  // optional
    married :    DS.attr('boolean',
             {defaultValue: false}), // boolean
    email :      DS.attr('string'),  // e-mail

    requiredFields : ['firstName', 'lastName', 'age'],
    numericFields : ['age'],
    booleanFields : ['married'],
    emailFields : ['email']

Elsewhere in your code you could be doing something like this:

var x = this.store.createRecord('person');
x.firstName = 'Austin'; // is OK
x.lastName = 'Powers'; // is OK
x.town = 'London'; // is OK
x.age = 'thirty'; // fails
x.married = 'not really'; // fails
x.email = 'fax only'; // fails
var ok = x.is_valid();
if( ok ) {
    console.log('All error-messages:', x.get('errors').get('messages'));

// or validate fields specifically:
if( !this.get('model').is_valid_field( 'firstName' ) ) {
    console.log('firstName' + ' has error:');
    this.get('model').get('errors').errorsFor( 'firstName' ).forEach(function(err){
    console.log('firstName' + ' is all good');

Those model-errors are very useful in your templates, where you could either use all error-messages, model.errors.messages or field-specific error-messages, model.errors.age.errors (=array where each error-item has a message).
More info regarding model-errors at: http://emberjs.com/api/data/classes/DS.Errors.html.

Read how and when to set error-messages in the file’s comment.
Good luck and I hope you can use it some day!