I am trying to write a regular expression to validate a password which must meet the following criteria:
I tried the following but it doesn't seem to work.
http://jsfiddle.net/many_tentacles/Hzuc9/
<input type='button' value='click' class='buttonClick' />
<input type='text' />
<div></div>
and...
$(".buttonClick").click(function () {
if ($("input[type=text]").filter(function () {
return this.value.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/);
})) {
$("div").text("pass");
} else {
$("div").text("fail");
}
});
Any ideas?
This question is related to
javascript
jquery
regex
validation
At least 8 = {8,}
:
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
Your regex only allows exactly 8 characters. Use {8,}
to specify eight or more instead of {8}
.
But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.
Source: Stackoverflow.com