Models

The first thing we need to do is build our validation rules. This will then generate a Mixin that you will be able to incorporate into your model or object.

// models/user.js

import Ember from 'ember';
import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
  username: validator('presence', true),
  password: [
    validator('presence', true),
    validator('length', {
      min: 4,
      max: 8
    })
  ],
  email: [
    validator('presence', true),
    validator('format', { type: 'email' })
  ],
  emailConfirmation: [
    validator('presence', true),
    validator('confirmation', {
      on: 'email',
      message: '{description} do not match',
      description: 'Email addresses'
    })
  ]
});

Once our rules are created and our Mixin is generated, all we have to do is add it to our model.

// models/user.js

export default DS.Model.extend(Validations, {
  'username': attr('string'),
  'password': attr('string'),
  'email': attr('string')
});

Objects

You can also use the generated Validations mixin on any Ember.Object or child of Ember.Object, like Ember.Component. For example:

// components/x-foo.js

import Ember from 'ember';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
  bar: validator('presence', true)
});

export default Ember.Component.extend(Validations, {
  bar: null
});
// models/user.js

export default Ember.Object.extend(Validations, {
  username: null
});

A Note on Testing & Object Containers

To lookup validators, container access is required, which can cause an issue with Ember.Object creation if the object is statically imported. The current fix for this is as follows.

Ember < 2.3.0

// routes/index.js

import User from '../models/user';

export default Ember.Route.extend({
  model() {
    var container = this.get('container');
    return User.create({ username: 'John', container })
  }
});

Ember >= 2.3.0

// routes/index.js

import User from '../models/user';

export default Ember.Route.extend({
  model() {
    return User.create(
     Ember.getOwner(this).ownerInjection(),
     { username: 'John' }
    );
  }
});

This also has ramifications for Ember Data model tests. When using Ember QUnit's moduleForModel (or Ember Mocha's setupModelTest), you will need to specify all validators that your model depends on:

moduleForModel('foo', 'Unit | Model | model', {
  needs: ['validator:presence']
});