Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Last active August 29, 2015 14:14
Show Gist options
  • Save dejanvasic85/bc82173413fa7120824f to your computer and use it in GitHub Desktop.
Save dejanvasic85/bc82173413fa7120824f to your computer and use it in GitHub Desktop.
Angular Strength Indicator
angular.module('passwordModule', [])
.controller('credentialsController', ['$scope',
function($scope) {
// Initialise the password as hello
$scope.credentials = {
password: 'hello'
};
}
])
.directive('passwordStrength', [
function() {
return {
require: 'ngModel',
restrict: 'E',
scope: {
password: '=ngModel'
},
link: function(scope, elem, attrs, ctrl) {
scope.$watch('password', function(newVal) {
scope.strength = isSatisfied(newVal && newVal.length >= 8) +
isSatisfied(newVal && /[A-z]/.test(newVal)) +
isSatisfied(newVal && /(?=.*\W)/.test(newVal)) +
isSatisfied(newVal && /\d/.test(newVal));
function isSatisfied(criteria) {
return criteria ? 1 : 0;
}
}, true);
},
template: '<div class="progress">' +
'<div class="progress-bar progress-bar-danger" style="width: {{strength >= 1 ? 25 : 0}}%"></div>' +
'<div class="progress-bar progress-bar-warning" style="width: {{strength >= 2 ? 25 : 0}}%"></div>' +
'<div class="progress-bar progress-bar-warning" style="width: {{strength >= 3 ? 25 : 0}}%"></div>' +
'<div class="progress-bar progress-bar-success" style="width: {{strength >= 4 ? 25 : 0}}%"></div>' +
'</div>'
}
}
])
.directive('patternValidator', [
function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
var patt = new RegExp(attrs.patternValidator);
var isValid = patt.test(viewValue);
ctrl.$setValidity('passwordPattern', isValid);
// angular does this with all validators -> return isValid ? viewValue : undefined;
// But it means that the ng-model will have a value of undefined
// So just return viewValue!
return viewValue;
});
}
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment