Skip to content

Instantly share code, notes, and snippets.

@lightsofapollo
Created November 9, 2011 21:03
Show Gist options
  • Save lightsofapollo/1353018 to your computer and use it in GitHub Desktop.
Save lightsofapollo/1353018 to your computer and use it in GitHub Desktop.
Validation Architecture
PSI.Validator = function(){
this.init.apply(this, arguments);
};
PSI.Validators.Presence = function(){
this.init.apply(this, arguments);
};
PSI.Validators.Presence = YAHOO.lang.augmentObject({
init: function(config){
this.message = config.message || this.message;
},
getMessage: function(field){
return Y.lang.sub(this.message, {
'field': field
});
},
validate: function(field, validator){
var attributes = validator.get('attributes');
if(!attributes[field] || attributes[field] !== ''){
validator.get('errors').add(
'fieldName',
this.getMessage(field)
);
}
}
});
PSI.Validator.register = function(validator, klass){
var extension = [];
extension[validator] = function(fields, options){
var instance = new klass(options), i;
for(i = 0; i < fields.length; i++){
this._validations.add(fields[i], instance);
}
};
YAHOO.lang.augmentObject(PSI.Validator.prototype, extension);
};
PSI.Validator.register('presenceOf', PSI.Validators.PresenceOf);
YAHOO.lang.augmentObject(PSI.Validator.prototype, {
_validations: {
'firstName': [validatorRef, validatorRef]
},
errors: new PSI.MessageContainer(),
register: function(validator, klass){
var extension = [];
this[validator] = function(fields, options){
var instance = new klass(options), i;
for(i = 0; i < fields.length; i++){
this._validations.add(fields[i], instance);
}
};
},
context: PSI.Model(),
// presenceOf: function(fields, options){
// var validator = new PSI.Validators.Presence(options), i;
// for(i = 0; i < fields.length; i++){
// this._validations.add(fields[i], validator);
// }
// },
validate: function(attrs, options){
var i = 0;
this.attributes = attrs;
PSI.YUI.each(this._validations, this._runValidators, this);
},
_runValidators: function(val, key){
var validators = this._validations.get(key), i = 0, validator;
if(validators){
for(i = 0; i < validators.length; i++){
validator = validators[i];
validator.validate(
key,
this,
this.context
);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment