Last active
August 29, 2015 14:15
-
-
Save msalahz/b56932269c1a117fca1c to your computer and use it in GitHub Desktop.
Extended Ember Validations Controller Mixin extend original ember validations component controller mixin with IsValid & IsInvalid properties for each validated property and model validation errors array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This mixin extend original ember validations component controller mixin with | |
// IsValid & IsInvalid properties for each validated property and model validation errors array | |
// Module import for Ember | |
import Ember from 'ember'; | |
// Module import for Ember-Validations component | |
import EmberValidations from 'ember-validations'; | |
// Module export for extended ember validations controller mixin definition | |
export default Ember.Mixin.create(EmberValidations.Mixin,{ | |
init() { | |
// this call is necessary to execute parent activate hook if existed and avoid overriding it | |
this._super(); | |
// get mixin reference | |
let mixin = this, | |
// get validated properties list | |
properties =_.uniq(_.map(Ember.get(mixin, 'validators'),validator=> validator.property)); | |
// Define IsValid & IsInvalid properties for each validated property | |
_.each(properties, function (property) { | |
// Define [propertyName]IsValid Ember computed property for validated property | |
Ember.defineProperty(mixin, property + 'IsValid', Ember.computed(property, function () { | |
return Ember.get(mixin, 'errors.' + property).length === 0; | |
})); | |
// Define [propertyName]IsInvalid Ember computed property for validated property | |
Ember.defineProperty(mixin, property + 'IsInvalid', Ember.computed(property, function () { | |
return Ember.get(mixin, 'errors.' + property).length > 0; | |
})); | |
}); | |
}, | |
// an Ember property that represent model validation errors array | |
modelErrors: Ember.computed('[email protected]', function () { | |
let mixin = this, // get mixin reference | |
messages = [], // error messages container | |
validators = _.keys(Ember.get(mixin, 'errors')); // get validation properties list | |
_.each(validators, function (validator) { | |
// push error messages for each validation property | |
messages.pushObjects(Ember.get(mixin, 'errors.' + validator)); | |
}); | |
// return all error messages | |
return messages; | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment