Ember Validations
WARNING
This addon is no longer actively developed. At DockYard we have switched over to using ember-changeset-validations together with ember-changeset.
We do still maintain this addon.
Installing
ember install ember-validations
Looking for help?
If it is a bug please open an issue on GitHub.
Usage
You need to mixin EmberValidations
into any Ember.Object
you want to add
validations to:
;; Controller;
You define your validations as a JSON object. They should be added to
the controller that represents the model in question.
The keys in the object should map to properties. If you pass a
JSON object as the value this will be seen as validation rules to apply
to the property. If you pass true
then the property itself will be
seen as a validatable object.
;; Controller;
Though not yet explicitly part of the API, you can also add validators to nested objects:
;; Component;
This is useful for things like Components which don't act as proxies, but again, until this is officially built into the project, YMMV.
Note: If you override the init function, you must call _super()
;; Controller;
Validators
Absence
Validates the property has a value that is null
, undefined
, or ''
Options
true
- Passing justtrue
will activate validation and use default messagemessage
- Any string you wish to be the error message. Overridesi18n
.
// Examplesabsence: trueabsence: message: 'must be blank'
Acceptance
By default the values '1'
, 1
, and true
are the acceptable values
Options
true
- Passing justtrue
will activate validation and use default messagemessage
- Any string you wish to be the error message. Overridesi18n
.accept
- the value for acceptance
// Examplesacceptance: trueacceptance: message: 'you must accept' accept: 'yes'
Confirmation
Expects a propertyConfirmation
to have the same value as
property
. The validation must be applied to the property
, not the propertyConfirmation
(otherwise it would expect a propertyConfirmationConfirmation
).
Options
true
- Passing justtrue
will activate validation and use default messagemessage
- Any string you wish to be the error message. Overridesi18n
.
// Examplesconfirmation: trueconfirmation: message: 'you must confirm'
Exclusion
A list of values that are not allowed
Options
message
- Any string you wish to be the error message. Overridesi18n
.allowBlank
- Iftrue
skips validation if value is emptyin
- An array of values that are excludedrange
- an array with the first element as the lower bound the and second element as the upper bound. Any value that falls within the range will be considered excluded
// Examplesexclusion: in: 'Yellow' 'Black' 'Red' exclusion: range: 5 10 allowBlank: true message: 'cannot be between 5 and 10'
Format
A regular expression to test with the value
Options
message
- Any string you wish to be the error message. Overridesi18n
.allowBlank
- Iftrue
skips validation if value is emptywith
- The regular expression to test with
// Examplesformat: with: /^+$/ allowBlank: true message: 'must be letters and numbers only'
Inclusion
A list of the only values allowed
Options
message
- Any string you wish to be the error message. Overridesi18n
.allowBlank
- Iftrue
skips validation if value is emptyin
- An array of values that are allowedrange
- an array with the first element as the lower bound the and second element as the upper bound. Only values that fall within the range will be considered allowed
// Examplesinclusion: in: 'Yellow' 'Black' 'Red' inclusion: range: 5 10 allowBlank: true message: 'must be between 5 and 10'
Length
Define the lengths that are allowed
Options
number
- Alias foris
array
- Will expand tominimum
andmaximum
. First element is the lower bound, second element is the upper bound.allowBlank
- Iftrue
skips validation if value is emptyminimum
- The minimum length of the value allowedmaximum
- The maximum length of the value allowedis
- The exact length of the value allowedtokenizer
- A function that should return a object that responds tolength
Messages
tooShort
- the message used when theminimum
validation fails. Overridesi18n
tooLong
- the message used when themaximum
validation fails. Overridesi18n
wrongLength
- the message used when theis
validation fails. Overridesi18n
// Exampleslength: 5length: 3 5length: is: 10 allowBlank: true length: minimum: 3 maximum: 5 messages: tooShort: 'should be more than 3 characters' tooLong: 'should be less than 5 characters' length: is: 5 { return value; }
Numericality
Will ensure the value is a number
Options
true
- Passing justtrue
will activate validation and use default messageallowBlank
- Iftrue
skips validation if value is emptyonlyInteger
- Will only allow integersgreaterThan
- Ensures the value is greater thangreaterThanOrEqualTo
- Ensures the value is greater than or equal toequalTo
- Ensures the value is equal tolessThan
- Ensures the value is less thanlessThanOrEqualTo
- Ensures the value is less than or equal toodd
- Ensures the value is oddeven
- Ensures the value is even
Messages
numericality
- Message used when value failes to be a number. Overridesi18n
onlyInteger
- Message used when value failes to be an integer. Overridesi18n
greaterThan
- Message used when value failes to be greater than. Overridesi18n
greaterThanOrEqualTo
- Message used when value failes to be greater than or equal to. Overridesi18n
equalTo
- Message used when value failes to be equal to. Overridesi18n
lessThan
- Message used when value failes to be less than. Overridesi18n
lessThanOrEqualTo
- Message used when value failes to be less than or equal to. Overridesi18n
odd
- Message used when value failes to be odd. Overridesi18n
even
- Message used when value failes to be even. Overridesi18n
// Examplesnumericality: truenumericality: messages: numericality: 'must be a number' numericality: odd: true messages: odd: 'must be an odd number' numericality: onlyInteger: true greaterThan: 5 lessThanOrEqualTo : 10
Presence
Validates the property has a value that is not null
, undefined
, or ''
Options
true
- Passing justtrue
will activate validation and use default messagemessage
- Any string you wish to be the error message. Overridesi18n
.
// Examplespresence: truepresence: message: 'must not be blank'
Uniqueness
Not yet implemented.
Conditional Validators
Each validator can take an if
or an unless
in its options
hash.
The value of the conditional can be an inline function, a string that
represents a property on the object, or a string that represents a
function on the object. The result should be a boolean.
note that if
is considered a keyword in IE8 and so you should put it
in quotes
// function form'model.firstName': presence: { return true; } // string form// if 'canValidate' is a function on the object it will be called// if 'canValidate' is a property object.get('canValidate') will be called'model.firstName': presence: unless: 'canValidate'
Custom Validators
With Ember-CLI
You can place your custom validators into
my-app/app/validators/{local,remote}/<name>
:
; ;
It is recommended that you separate between local
and remote
validators. However, if you wish you can place your validator into
my-app/app/validators/<name>
. However, any similarly named validator
in local/
or remote/
has a higher lookup presedence over those in
validators/
.
The "native" validators that come with ember-validations
have the
lowest lookup priority.
Without Ember-CLI
You can add your validators to the global object:
EmberValidationsvalidatorslocal<ClassName> =EmberValidationsvalidatorsBase;
Creating
To create a new validator you need to override the call
function. When
the validator is run its call
function is what handles determining if
the validator is valid or not. Call has access to this.model
,
this.property
. If the validation fails you must push the failing
message onto the validator's this.errors
array. A simple example of a
validator could be:
;; ;
You may want to create a more complex validator that can observer for
changes on multiple properties. You should override the init
function
to accomplish this:
;; ;
The init
function is given access to the this.options
which is simply
a POJO of the options passed to the validator.
dependentValidationKeys
is the collection of paths relative to
this.model
that will be observed for changes. If any changes occur on
any given path the validator will automatically trigger.
Inline Validators
If you want to create validators inline you can use the
validator
function that is part of the ember-validations
export:
; User;
Inside the validator
function you have access to this.model
which is
a reference to the model. You must return an error message that will
be attached to the errors array for the property it is created on.
Return nothing for the validator to pass.
Alternatively if the property doesn't have any additional validations you can use a more concise syntax:
User;
Running Validations
Validations will automatically run when the object is created and when
each property changes. isValid
states bubble up and help define the
direct parent's validation state. isInvalid
is also available for convenience.
If you want to force all validations to run simply call .validate()
on the object. isValid
will be set to true
or false
. All validations are run as deferred objects, so the validations will
not be completed when validate
is done. So validate
returns a promise, call then
with a function containing the code you want to run after the validations have successfully
completed.
user;
Inspecting Errors
After mixing in EmberValidations
into your object it will now have a
.errors
object. All validation error messages will be placed in there
for the corresponding property. Errors messages will always be an array.
;; Object;
; user = User;user
Testing
With Ember QUnit
For Ember Validations to work with Ember QUnit,
you must define all your validations in the needs
property of the moduleFor
call. This will ensure Ember QUnit's isolated container will be able to locate
the validations during testing.
; ; ;
Where UserEditController
uses the built-in presence
and length
validators,
and the locally defined name
and email
validators.
Test Helpers
To test whether your Ember validations are working correctly, you can use the test helpers:
testValidPropertyValues(propertyName, values [, context ])
testInvalidPropertyValues(propertyName, values [, context ])
propertyName
(String): the property that you are validating.values
(Array): an array of property values to check.context
(function) optional: if specified, this function will be called with the object under test as an argument. See example below.
;; ; ;;
If a property's validation relies on another property, you can pass a context to the test helper:
; ;
i18n
When you use ember-i18n your Ember.I18n.translations
object should contain the following keys under the errors
key:
EmberI18ntranslations = errors: inclusion: "is not included in the list" exclusion: "is reserved" invalid: "is invalid" confirmation: "doesn't match {{attribute}}" accepted: "must be accepted" empty: "can't be empty" blank: "can't be blank" present: "must be blank" tooLong: "is too long (maximum is {{count}} characters)" tooShort: "is too short (minimum is {{count}} characters)" wrongLength: "is the wrong length (should be {{count}} characters)" notANumber: "is not a number" notAnInteger: "must be an integer" greaterThan: "must be greater than {{count}}" greaterThanOrEqualTo: "must be greater than or equal to {{count}}" equalTo: "must be equal to {{count}}" lessThan: "must be less than {{count}}" lessThanOrEqualTo: "must be less than or equal to {{count}}" otherThan: "must be other than {{count}}" odd: "must be odd" even: "must be even"
Other Resources
Authors
We are very thankful for the many contributors
Versioning
This library follows Semantic Versioning
Want to help?
Please do! We are always looking to improve this library. Please see our Contribution Guidelines on how to properly submit issues and pull requests.
Legal
DockYard, LLC © 2016