Skip to content

Instantly share code, notes, and snippets.

@icfantv
Last active February 10, 2016 19:40
Show Gist options
  • Save icfantv/da3cf5ead57ad64dabeb to your computer and use it in GitHub Desktop.
Save icfantv/da3cf5ead57ad64dabeb to your computer and use it in GitHub Desktop.
Username Validation
vm.username = function($viewValue, $modelValue, scope) {
// check if username matches regex before validating
var value = $modelValue || $viewValue, deferred = $q.defer();
if (UserConfig.ID_REGEX.test(value)) {
scope.options.templateOptions.loading = true;
UserService.username(value).then(function() {
deferred.reject(false);
scope.options.templateOptions.loading = false;
},
function(error) {
// server returns a 404 if a user w/ the username can't be found.
// this is ok
if (error && error.status === 404) {
deferred.resolve(true);
}
else {
deferred.resolve(false);
}
scope.options.templateOptions.loading = false;
});
}
else {
return $q(function (resolve) {
scope.options.templateOptions.loading = false;
resolve();
});
}
return deferred.promise;
};
vm.username = function($viewValue, $modelValue, scope) {
var value = $modelValue || $viewValue;
return $q(function(resolve, reject) {
if (UserConfig.ID_REGEX.test(value)) {
scope.options.templateOptions.loading = true;
UserService.username(value).then(function() {
reject(false);
}).catch(function(error) {
if (error && error.status === 404) {
resolve(true);
}
else {
resolve(false);
}
}).finally(function() {
scope.options.templateOptions.loading = false;
});
}
else {
scope.options.templateOptions.loading = false;
resolve();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment