Conditional Validation in Ember

Often in real world applications you’ll find yourself needing to set up conditional validation rules. e.g. Require this if that === “foo”. The Ember Changeset Conditional Validations addon adds this functionality to Ember Changeset Validations.

In our quick example we have a form to request a extension to some homework. Our model has two fields

  • reason
  • notes

Reason is an enum containing many common excuses e.g.

  • Dog ate it
  • Illness
  • Couldnt find it
  • Internet was down
  • Lost it in the great Mt. Gox hack of 2014
  • Other

The reason field is required. If the user selects other we also want to make sure the notes field is required.

// app/validations/extension-request.js

import {
  validateLength,
  validatePresence,
} from "ember-changeset-validations/validators";
import validateSometimes from "ember-changeset-conditional-validations/validators/sometimes";

export default {
  reason: [validatePresence(true)],
  notes: validateSometimes(
    [validatePresence(true), validateLength({ min: 32 })],
    function (/*changes, content*/) {
      // This isnt ember's get - it's implemented by ember-changeset-conditional-validations
      // so we will silence the lint error

      /* eslint-disable ember/no-get */
      return this.get("reason") === "other";
    }
  ),
};

validateSometimes() takes 2 arguments. The first is a validator or an array of validators you want applied to the attribute. The second argument is a callback function which represents the condition. If the condition callback returns true, the rules will be added.

View the addons readme for more examples.

Jim Wardlaw

Developer, Designer, UX Zealot. Ember & Tailwind