Skip to content

Instantly share code, notes, and snippets.

@s22su
Created October 19, 2015 13:14
Show Gist options
  • Select an option

  • Save s22su/d2d02899edde02e56041 to your computer and use it in GitHub Desktop.

Select an option

Save s22su/d2d02899edde02e56041 to your computer and use it in GitHub Desktop.
Angular password validator
angular.module('app').directive('strongSecret', function() {
return {
// limit usage to argument only
restrict: 'A',
// require NgModelController, i.e. require a controller of ngModel directive
require: 'ngModel',
// create linking function and pass in our NgModelController as a 4th argument
link: function(scope, element, attr, ctrl) {
// please note you can name your function & argument anything you like
function customValidator(ngModelValue) {
// check if contains uppercase
// if it does contain uppercase, set our custom `uppercaseValidator` to valid/true
// otherwise set it to non-valid/false
if (/[A-Z]/.test(ngModelValue)) {
ctrl.$setValidity('uppercaseValidator', true);
} else {
ctrl.$setValidity('uppercaseValidator', false);
}
// check if contains number
// if it does contain number, set our custom `numberValidator` to valid/true
// otherwise set it to non-valid/false
if (/[0-9]/.test(ngModelValue)) {
ctrl.$setValidity('numberValidator', true);
} else {
ctrl.$setValidity('numberValidator', false);
}
// 8 char or more check
if (ngModelValue.length === 8 || ngModelValue.length > 8) {
ctrl.$setValidity('charactersValidator', true);
} else {
ctrl.$setValidity('charactersValidator', false);
}
// we need to return our ngModelValue, to be displayed to the user(value of the input)
return ngModelValue;
}
// we need to add our customValidator function to an array of other(build-in or custom) functions
// I have not notice any performance issues, but it would be worth investigating how much
// effect does this have on the performance of the app
ctrl.$parsers.push(customValidator);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment