0

I want to create some kind of password checker with regex and update progress bar depending on password strength.

So I created array of objects because I need to check regex and if input value matches regex then pass percentages to the progress bar.

var passwordsRegex =  [{ weak: '^[a-z]+$', percentage: 20}, 
            { good: '[a-zA-Z]+$', percentage: 50}, 
            { normal: '^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$', percentage: 70},
            { strong: '(?=^.{8,}$)(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$', percentage: 100}];

$('#pass').on('keyup', function(e) {
    var value = $(this).val();

    if(value == passwordsRegex[?].?) {
        ...
    }
});

function progress(percent, $element) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");
}

progress(50, $('#progressBar'))

Can someone help how to check if value matches with one of the regex without writing a lot of conditional statements.

Thanks

Medf101
  • 107
  • 1
  • 5
  • Your strong regex won't work, see [this thread](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped). – Wiktor Stribiżew Sep 20 '18 at 20:59

1 Answers1

0

First, you need to change the array so that the regexp is in a property with the same name. If you want a descriptive name, put that in another property:

var passwordsRegex =  [
    { description: "strong", regex: '(?=^.{8,}$)(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$', percentage: 100},
    { description: "normal", regex: '^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$', percentage: 70},
    { description: "good", regex: '[a-zA-Z]+$', percentage: 50}, 
    { description: "weak", regex: '^[a-z]+$', percentage: 20},
];

Use a for loop to test each regexp, and stop when one of them succeeds (I've reordered them to have the strongest one first).

$('#pass').on('keyup', function(e) {
    const value = $(this).val();
    for (let i = 0; i < passwordsRegex.length; i++) {
        if (value.match(passwordsRegex[i].regex) {
            progress(passwordsRegex[i].percentage, $("#progressBar"));
            break;
        }
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612