Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Dynamic Regular Expressions in javascript based on pre-defined settings

I have a pre-defined settings to built password and those are

  1. Minimum length
  2. Using Alphabets (true or false)
  3. Using Numeric (true or false)
  4. Using Case Characters
  5. Using Alphabets (allow only ,‘#&-_“.)

I created a java-script function to build the same

function BuildRegex(alphabets, numerics, cases, specials) {
var pattern = "^[";
if (alphabets == "True")
    pattern += "a-z";
if (cases == "True")
    pattern += "A-Z";
if (numerics == "True")
    pattern += "0-9";
if (specials == "True")
    pattern += ",‘#&-_“.";
pattern += "]*$";
return pattern;

}

and I used the pattern as:

var re = new RegExp(pattern);
if (!re.test(input)) {
  $("#lblError").show();
}

But it is not working :(

Help needed!!

Sample code :

<html>
<head>
Add Jquery CDN here
<script type="text/javascript">
function BuildRegex(alphabets, numerics, cases, specials) {
        var pattern = "^[";
        if (alphabets == "True")
            pattern += "a-z";
        if (cases == "True")
            pattern += "A-Z";
        if (numerics == "True")
            pattern += "0-9";
        if (specials == "True")
            pattern += ",‘#&-_“.";
        pattern += "]*$";
        return pattern;
    }

$(document).on("change", "#txtPassword", function () {
        debugger;
        var input = $(this).val();
        if ($.trim(input) != "") {
            var pattern = BuildRegex("True", "False", "True", "True");
            var re = new RegExp(pattern);
            if (!re.test(input)) {
                $("#lblError").show();
            }
            else {
                $("#lblError").hide();
            }
        }
        else {
            $("#lblError").hide();
        }
    });
</script>
</head>
<body>
<input type="text" id="txtPassword" />
<span id="lblError" style="display:none;">Invalid characters in password.</span>
</body>

Debugging Image

Comments