Don’t put the /
around the expression. Then you can convert it to a regular expression with new RegExp
, and test the password with it. You can loop with .every()
, which will perform tests as long as they’re successful.
var pwdarray = {
"pwd": [{
"TEXT": "Password must be at least 6 character(s) long.",
"EXPRESSION": "^(.){6,}$"
},
{
"TEXT": "Password must contain at least 1 lowercase letter(s).",
"EXPRESSION": "[a-z]"
}
]
}
$("#check").click(function() {
var pswd = $("#pass").val();
$("#error").text("Password is good").addClass('valid').removeClass('invalid');
pwdarray.pwd.every(({
TEXT: text,
EXPRESSION: exp
}) => {
if (!new RegExp(exp).test(pswd)) {
$("#error").text(text).addClass('invalid').removeClass('valid');
return false;
} else {
return true;
}
});
});
.invalid {
color: red;
}
.valid {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pass">
<button id="check">Check</button>
<div id="error"></div>
solved how to use json array for password validation?