Created
October 1, 2016 15:04
-
-
Save goors/ecfa7706c35dff0dd2aa769e8b5c1f4a to your computer and use it in GitHub Desktop.
Password strength directive for angular.
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
.directive('checkStrength', function () { | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs){ | |
function scorePassword(pass) { | |
var score = 0; | |
if (!pass) | |
return score; | |
// award every unique letter until 5 repetitions | |
var letters = new Object(); | |
for (var i=0; i<pass.length; i++) { | |
letters[pass[i]] = (letters[pass[i]] || 0) + 1; | |
score += 5.0 / letters[pass[i]]; | |
} | |
// bonus points for mixing it up | |
var variations = { | |
digits: /\d/.test(pass), | |
lower: /[a-z]/.test(pass), | |
upper: /[A-Z]/.test(pass), | |
nonWords: /\W/.test(pass), | |
} | |
var variationCount = 0; | |
for (var check in variations) { | |
variationCount += (variations[check] == true) ? 1 : 0; | |
} | |
score += (variationCount - 1) * 10; | |
return parseInt(score); | |
} | |
scope.$watch(attrs.checkStrength, function(value) { | |
if(angular.isDefined(value)){ | |
if (scorePassword(value) > 80) { | |
scope.strength = 'strong'; | |
} else if (scorePassword(value) > 60) { | |
scope.strength = 'medium'; | |
} else { | |
scope.strength = 'weak'; | |
} | |
} | |
}); | |
} | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment