ember-cli
package, which adds validation support to your Ember-Data models.
This README outlines the details of collaborating on this Ember addon.
This Ember cli addons borns from the necessity of having some sort of similar validation support like we have on Rails with Active Record Validations.
Install Ember-model-validator is easy as:
npm install ember-model-validator --save-dev
- Presence
- Acceptance
- Absence
- Format
- Length
- Color
- ZipCode
- Subdomain
- URL
- Inclusion
- Exclusion
- Numericality
- Password*
- CustomValidation
- Relations
All validators accept the following options
message
option. Overwrites the default message.errorAs
option. Sets the key name to be used when adding errors (default to property name).
A value is not present if it is empty or a whitespace string. It uses Ember.isBlank method.
validations: {
name: {
presence: true
}
}
These values: ['1', 1, true]
are the acceptable values. But you can specify yours with the accept
option.
validations: {
acceptConditions: {
acceptance: {accept: 'yes'}
}
}
The
accept
option receives either a string or an array of acceptable values.
Validates that the specified attributes are absent. It uses Ember.isPresent method.
validations: {
login: {
absence: true
}
}
Speficy a Regexp to validate with. It uses the match() method from String.
validations: {
legacyCode:{
format: { with: /^[a-zA-Z]+$/ }
}
}
Speficy the lengths that are allowed.
- A
number
. The exact length of the value allowed (Alias foris
). - An
array
. Will expand tominimum
andmaximum
. First element is the lower bound, second element is the upper bound. is
option. The exact length of the value allowed.minimum
option. The minimum length of the value allowed.maximum
option. The maximum length of the value allowed.
validations: {
socialSecurity: {
length: 5
},
nsaNumber: {
length: [3, 5]
},
chuncaluchoNumber: {
length: { is: 10, message: 'this is not the length of a chuncalucho' }
},
hugeName:{
length: {
minimum: 3,
maximum: 5
}
}
}
Validates the proper fortmat of the email.
validations: {
email: {
email: true
}
}
The value must be a correct zipcode. Regexp used /^\b\d{5}(-\d{4})?\b$/i
.
validations: {
postalCode:{
zipCode: true
}
}
The value must be a correct Hexadecimal color.
validations: {
favoritColor:{
color: true
}
}
The value must a well formatted subdomain. Here you can also specify reserved words.
validations: {
mySubdomain:{
subdomain:{ reserved:['admin','blog'] }
}
}
The value must a well formatted URL.
validations: {
myBlog: {
URL: true
}
}
The value has to be included in a given set.
validations: {
name:{
inclusion: { in: ['Jose Rene', 'Aristi Gol', 'Armani'] }
}
}
The value can't be included in a given set.
validations: {
name:{
exclusion: { in: ['Gionvany Hernandez', 'Wilder Medina'] }
}
}
The value has to have only numeric values.
validations: {
lotteryNumber:{
numericality: true
}
}
Define a custom callback funciton to validate the model's value. The validation callback is passed 3 values: the key, value, model's scope. return true (or a truthy value) to pass the validation, return false (or falsy value) to fail the validation.
validations: {
lotteryNumber: {
custom: funciton(key, value, model){
return model.get('accountBalance') > 1 ? true : false;
}
}
}
this has the same action as above except will use a custom message insetad of the default.
validations: {
lotteryNumber: {
custom: {
validation: funciton(key, value, model){
return model.get('accountBalance') > 1 ? true : false;
},
message: 'You can't win off of good looks and charm.'
}
}
}
A set of validators which are especially useful for validating passwords. Be aware that these all of these password-aimed validations will work standalone and carry the same common options with the rest of the validations. They don't only work for passwords!
mustContainCapital
(capital case character).mustContainLower
(lower case character).mustContainNumber
mustContainSpecial
length
(explained in-depth above).
validations: {
password: {
presence: true,
mustContainCapital: true,
mustContainLower: true,
mustContainNumber: true,
mustContainSpecial: {
message: 'One of these chacters is required: %@',
acceptableChars: '-+_!@#$%^&*.,?()'
},
length: {
minimum: 6
}
},
someOtherThing: {
mustContainSpecial: true
}
}
This validator will run the validate()
function for the specific relation. If it's a DS.hasMany
relation then it will loop through all objects.
Note: The relations have to be
embedded
or the promise has to be already resolved.
validations: {
myHasManyRelation:{
relations: ['hasMany']
},
myBelongsToRelation:{
relations: ['belongsTo']
}
}
Ember-model-validator provides a mixin to be included in your models for adding validation support. This mixin can be imported from your app's namespace (e.g. ../mixins/model-validator
in your models).
By including Ember-model-validator's mixin into your model, this will have a validate
function available, it is a synchronous function which returns either true or false. You can also pass an option hash for excluding or forcing certain attributes to be validated.
//Using `except`
myModel.validate({except:['name', 'cellphone']});
//Using `only`
myModel.validate({only:['favoritColor', 'mainstreamCode']});
import DS from 'ember-data';
import Validator from '../mixins/model-validator';
export default DS.Model.extend(Validator,{
name: DS.attr('string'),
login: DS.attr('string'),
secondName: DS.attr('string'),
email: DS.attr('string'),
bussinessEmail: DS.attr('string'),
favoritColor: DS.attr('string'),
legacyCode: DS.attr('string'),
mainstreamCode: DS.attr('string'),
lotteryNumber: DS.attr('number'),
alibabaNumber: DS.attr('number'),
acceptConditions: DS.attr('boolean'),
postalCode: DS.attr('string'),
mySubdomain: DS.attr('string'),
myBlog: DS.attr('string'),
otherFakes: DS.hasMany('other-model'),
otherFake: DS.belongsTo('other-model'),
validations: {
name: {
presence: { errorAs:'profile.name' },
inclusion: { in: ['Jose Rene', 'Aristi Gol', 'Armani'], message: 'Solo verde a morir' }
},
login: {
absence: true
},
secondName: {
exclusion: { in: ['Gionvany Hernandez', 'Wilder Medina'], message: 'Que iNrresponsabilidad' }
},
bussinessEmail: {
presence: { message: 'sup dude, where\'s da email' },
email: { message: 'Be professional ma men' }
},
favoritColor:{
color: { message: 'not a hex color' }
},
email: {
presence: true,
email: true
},
mySubdomain:{
subdomain:{ reserved:['admin','blog'], message: 'this subdomain is super invalid' }
},
myBlog: {
URL: true
},
mainstreamCode: {
format: { with: /^[a-zA-Z]+$/, message: 'nu nu, that\'s not the format' }
},
legacyCode:{
format: { with: /^[a-zA-Z]+$/ }
},
alibabaNumber: {
numericality: { message: 'is not abracadabra' }
},
lotteryNumber: {
numericality: true
},
acceptConditions: {
acceptance: true
},
postalCode:{
zipCode: true
},
otherFakes:{
relations: ['hasMany']
},
otherFake:{
relations: ['belongsTo']
}
}
});
After setting the validationces on your model you will be able to:
import Ember from 'ember';
export default Ember.Route.extend(
{
actions: {
saveFakeModel: function() {
var _this = this,
fakeModel = this.get('model');
if(fakeModel.validate()){
fakeModel.save().then(
// Success
function() {
// Alert success
console.log('ooooh yeah we just saved the FakeModel...');
},
// Error handling
function(error) {
// Alert failure
console.log('There was a problem saving the FakeModel...');
console.log(error);
}
);
}else{
fakeModel.get('errors');
}
},
}
}
);
ember test
ember test --server
ember build
For more information on using ember-cli, visit http://www.ember-cli.com/.