Skip to content

Instantly share code, notes, and snippets.

@rafaell-lycan
Last active November 30, 2015 19:06
Show Gist options
  • Save rafaell-lycan/14a7b7c145e4fac0d1a7 to your computer and use it in GitHub Desktop.
Save rafaell-lycan/14a7b7c145e4fac0d1a7 to your computer and use it in GitHub Desktop.
ValidatorService.js
(function() {
'use strict';
angular
.module('auth')
.factory('Validator', Validator);
Validator.$inject = ['$q', '$timeout'];
function Validator($q, $timeout) {
let _model = {}, _collections = {};
function bind(ctrlModel) {
_model = ctrlModel;
}
function getModel() {
return _model;
}
function Validation(rule, errMessage) {
return {
run: function() {
return rule();
},
message: errMessage || '',
};
}
function addRule(rule, errMessage) {
return new Validation(rule, errMessage);
}
function addCollection(collectionName, rules) {
_collections[collectionName] = rules || [];
}
function validate(collectionName) {
let defer = $q.defer();
$timeout(() => {
_collections[collectionName].forEach((rule, i) => {
if (!rule.run()) return defer.reject(rule.message);
});
defer.resolve();
}, 100);
return defer.promise;
}
return {
model: _model,
getModel: getModel,
addCollection: addCollection,
bind: bind,
addRule: addRule,
validate: validate,
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment