ember-validations
ember-validations copied to clipboard
Ember-Validations - An Ember.js library for handling object validations
Ember Validations 
Warning: This project is no longer updated. dockyard/ember-validations is a great similar library
Ember-validations is a Ember.js library that can handle object validations. If you have to check the validity of object properties, this library does it for you. You just have to declare which property you want to validate, and which kind of validation you want for this property.
This library is inspired by the validations of the Ruby gem ActiveRecord.
Getting ember-validations
Currently you must build ember-validations yourself. Clone the repository, run bundle then rake dist. You'll find ember-validations.js in the dist directory.
Example
App.User = Ember.Object.extend( Ember.Validations, {
country: null,
validations: {
name: {
presence: true
},
age: {
numericality: true,
length: {
moreThan: 21,
lessThan: 99
},
},
email: {
format: /.+@.+\..{2,4}/
}
}
});
Usage
- Extend
Ember.Validationsmixin:
App.User = Ember.Object.extend( Ember.Validations );
- Define its validations by settings them in its
validationproperty. The following example is apresencevalidation that ensures thenameof theUseris set:
App.User = Ember.Object.extend( Ember.Validations, {
validations: {
name: {
presence: true
}
}
});
- Launch validations on an object using the
validatemethod.
var user = App.User.create();
user.validate();
- The
isValidproperty is now set astrue, orfalsedepending on the validations result:
user.get('isValid'); // => false
Errors
Once the validate method is called, if some properties are invalid, the validationErrors property is updated.
For the example below, we assume we have a User defined like this:
App.User = Ember.Object.extend( Ember.Validations, {
validations: {
name: {
presence: true
},
age: {
numericality: {
moreThanOrEqualTo: 21,
lessThan: 99
}
},
'address.zipCode': {
numericality: true
}
}
});
An error is defined by a key, a message, and a path.
There are three types of error messages:
allMessages: It returns all errors. Each of them is an array that contains thepathand themessageerror, as follows:
user.get('validationErrors.allMessages');
Will return this array:
[
[ "name", "can't be blank" ],
[ "age", "is not greater than or equal to 21" ],
[ "age", "is not less than 99" ],
[ "address.zipCode", "is not a number" ]
]
fullMessages: It has the same behaviour asallMessages, except that errors are thepathand themessageconcatenated:
[
"name can't be blank",
"age is not greater than or equal to 21",
"age is not less than 99",
"address.zipCode is not a number"
]
messages: It returns only errors messages corresponding the path specified (agehere):
user.get('validationErrors.age.messages');
Will return this array:
[
"is not greater than or equal to 21",
"is not less than 99"
]
Remark: There are also keys and allKeys properties that works like messages, but for error keys.
Validators
Presence
It ensures the attribute is not blank.
You can define it as follow, in the validation property:
name: {
presence: true
}
Length
The length validation is used to check the length of the property.
Three options can be passed:
minimumismaximum
Example:
password: {
length: {
minimum: 6,
maximum: 12
}
}
When no option is specified, the is option is set by default:
phone: {
length: 10
}
Is equivalent to:
phone: {
length: {
is: 10
}
}
Numericality
The numericality validation can have multiple usage, defined by its option:
onlyIntegergreaterThangreaterThanOrEqualTolessThanlessThanOrEqualToequalTo
Example:
amount: {
numericality: {
moreThanOrEqualTo: 1,
lessThan: 100
}
}
When no option is passed, it just add an error if the value can not be parsed as a number (e.g. when the value contains letter):
amount: {
numericality: true
}
Format
It validates whether the attribute has (or not, depending on the option specified) the supplied regexp.
The simplest way to use it is as follow:
email: {
format: /.+@.+\..{2,4}/
}
But you can specify options with and/or without:
password: {
format: {
with: /[a-zA-Z]+/,
without: /[0-9]+/
}
}
Match
It validates whether the contents of 2 properties are the same
There is only 1 option:
match
Example:
password: {
match: {
property: {
"confirmPassword"
}
}
},
confirmPassword: {
....
}
Single property validation
Sometime you could want to validate only one property.
You can do this by calling validateProperty('attributeName') instead of validate().
It will also update the isValid property if the validity of the object changes.
Runtime validations
A function can be passed to the validations options for runtime validations. An example could be:
age: {
length: {
moreThan: function() {
return this.get('country') === 'France' ? 18 : 21;
}
}
}
Skipping validations
Validators will, by default, skip validations on blank values.
The presence validation ignores this option for obvious reasons.
You can disable this behaviour by setting the allowBlank option to false.
Custom validations
On-the-fly
You can define custom validation function, like this:
password: {
myCustomValidator: {
validator: function(object, attribute, value) {
if (!value.match(/[A-Z]/)) {
object.get('validationErrors').add(attribute, 'invalid');
}
}
}
}
Write your own validator
You can write your own validator easily.
- Define your validator in the
Ember.Validatorsnamespace. It allows to use via its name. For example, writing anEmber.Validators.FooValidatorallows you to use it using:
validations: {
name: {
foo: true
}
}
-
Extend
Ember.Validatorand implement the_validatemethod. Just take a look at the existing validators to see how to write it. -
That's all folks!
Building Ember-Validations
- Run
rake disttask to build Ember-validations.js. Two builds will be placed in thedist/directory.
ember-validations.jsis a unminified version (generally used for development)ember-validations.min.jsis the minified version, production ready
If you are building under Linux, you will need a JavaScript runtime for
minification. You can either install nodejs or gem install therubyracer.
Build API Docs
NOTE: Require node.js to generate it.
Preview API documentation
Run rake docs:preview.
The docs:preview task will build the documentation and make it available at http://localhost:9292/index.html
Build API documentation
Run rake docs:build
The HTML documentation is built in the docs directory
How to run Unit Tests
Setup
-
Install Ruby 1.9.2+. There are many resources on the web can help; one of the best is rvm.
-
Install Bundler:
gem install bundler -
Run
bundleinside the project root to install the gem dependencies.
In Your Browser
-
To start the development server, run
rackup. -
Then visit: `http://localhost:9292/tests/index.html
From the CLI
-
Install phantomjs from http://phantomjs.org
-
Run
rake testto run a basic test suite or runrake test[all]to run a more comprehensive suite.