Last active
February 10, 2016 19:40
-
-
Save icfantv/da3cf5ead57ad64dabeb to your computer and use it in GitHub Desktop.
Username Validation
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
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; | |
}; |
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
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