jeudi 26 mai 2016

Shorten javascript RegExp Conditional

I have the following javascript function that runs on keyup inside of an input:

            var passwordInput = document.getElementsByName("newPassword")[0].value;

            var upperCase= new RegExp('[A-Z]');
            var lowerCase= new RegExp('[a-z]');
            var numbers = new RegExp('[0-9]');

            if ( passwordInput.match(lowerCase) ) {
                $('.strength-check__rule[data-index="1"]').addClass('check-rule--pass');
            } else {
                $('.strength-check__rule[data-index="1"]').removeClass('check-rule--pass');
            }

            if (passwordInput.match(upperCase)) {
                $('.strength-check__rule[data-index="2"]').addClass('check-rule--pass');
            } else {
                $('.strength-check__rule[data-index="2"]').removeClass('check-rule--pass');
            }

            if(passwordInput.match(numbers)) {
                $('.strength-check__rule[data-index="3"]').addClass('check-rule--pass');
            } else {
                $('.strength-check__rule[data-index="3"]').removeClass('check-rule--pass');
            }

            if(passwordInput.length >= 8) {
                $('.strength-check__rule[data-index="4"]').addClass('check-rule--pass');
            } else {
                $('.strength-check__rule[data-index="4"]').removeClass('check-rule--pass');
            }

The addClasses inside of each conditional simply add a class to an li to show that that condition has been met. I am wondering if anyone has any tips on how I could shorten this or make it more concise, specifically the first three conditions that are very similar.

Aucun commentaire:

Enregistrer un commentaire