Last active
November 30, 2015 19:06
-
-
Save rafaell-lycan/14a7b7c145e4fac0d1a7 to your computer and use it in GitHub Desktop.
ValidatorService.js
This file contains hidden or 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
(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