Skip to content

Instantly share code, notes, and snippets.

@Hounddog
Created July 9, 2014 13:47
Show Gist options
  • Save Hounddog/9f6c36016f010c3816a9 to your computer and use it in GitHub Desktop.
Save Hounddog/9f6c36016f010c3816a9 to your computer and use it in GitHub Desktop.
Password Strength
/*jshint evil:true */
'use strict';
angular.module('angular-password-strength', [])
.directive('passwordStrength', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if(viewValue) {
var strength;
var regex;
scope.calculations = [];
var calc = function (viewValue, pattern, formula){
var len = viewValue.length;
var n = 0;
if(viewValue.match(pattern)) {
n = viewValue.match(pattern).length;
}
var x = eval(formula);
return {formula:formula, pattern:pattern, length:len, n:n, x:x};
};
/* Additions */
//Character Length +(n*4)
scope.calculations.charLength = calc(viewValue, /./, '(len*4)');
strength = scope.calculations.charLength.x;
//lowercase letters +((len-n)*2)
scope.calculations.lowercaseLetters = calc(viewValue, /[a-z]/g, '((len-n)*2)');
strength += scope.calculations.lowercaseLetters.x;
//uppercase letters +((len-n)*2)
scope.calculations.uppercaseLetters = calc(viewValue,/[A-Z]/g, '((len-n)*2)');
strength += scope.calculations.uppercaseLetters.x;
//numbers +(n*4)
scope.calculations.numbers = calc(viewValue,/[0-9]/g, '(n*4)');
strength += scope.calculations.numbers.x;
//symbols +(n*6)
scope.calculations.symbols = calc(viewValue,/[-!$%^&*()_+|~=`{}\[\]:;<>?,.\/]/g, '(n*6)');
strength += scope.calculations.symbols.x;
/* Deductions */
//only letters -len
scope.calculations.onlyLetters = calc(viewValue,/^[a-zA-Z]+$/, '-len');
strength += scope.calculations.onlyLetters.x;
//only numbers -len
scope.calculations.onlyNumbers = calc(viewValue,/^[0-9]+$/, '-len');
strength += scope.calculations.onlyNumbers.x;
//consecutive numbers
scope.calculations.consecutiveNumbers = calc(viewValue,/\d\d/g, '-len');
strength += scope.calculations.consecutiveNumbers.x;
var count = 0;
//Check for consecutive Lowercase letters
regex = /([a-z]){2,}/g;
if(viewValue.match(regex)) {
var consecutiveLowercaseLetters = viewValue.match(regex);
consecutiveLowercaseLetters.forEach(function(entry){
count += (entry.length -1);
});
strength -= count*2;
}
//Check repeated characters
regex = /([a-z0-9-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/])\1+/gi;
if(viewValue.match(regex)) {
var repeated = viewValue.match(regex);
count = 0;
repeated.forEach(function(entry){
count += (entry.length -1);
});
scope.repeated = {count:count, value: count};
strength -= count;
}
scope.strength =strength;
console.log(scope.calculations);
if( strength < 70 ) {
ctrl.$setValidity('weak', false);
} else {
ctrl.$setValidity('weak', true);
}
}
return viewValue;
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment