JavaScript密码验证无效

时间:2011-07-26 11:26:27

标签: javascript

我使用这个来进行密码匹配,但是如果有人编辑它就行不通了

 <html>
<head>

<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

reason += validatePassword(theForm.pw1);

if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  alert("All fields are filled correctly");
  return false;
}

function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a Password.\n";
    } else if ((fld.value.length < 3) || (fld.value.length > 15)) {
        error = "The Password is the wrong length. \n";
        fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The Password contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The Password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
   return error;

}  
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}
</script>
</head>

<body>
<form onsubmit="return validateFormOnSubmit(this)" >

<table border=0>
  <tr>
    <td><label for="pw1">Password:</label></td>
    <td><input type="password" name="pw1" size="20" id="password" /></td>
  </tr>
  <tr>
    <td><label for="pw2">Confirm Password:</label></td>
    <td><input type="password" name="pw2" size="20" id="confPassword" /></td>
  </tr>
<tr>
<td colspan=2 align=center><input type=submit value="Submit!"></td>
</tr>
</table>
</form>
</body>
</html>

它的工作,但我也想匹配密码。但我无法做到这一点怎么办?

1 个答案:

答案 0 :(得分:2)

只需添加另一张支票并传递第二个密码框:http://jsfiddle.net/n9mL4/1/

validatePassword(theForm.pw1, theForm.pw2);

... } else if(fld.value != fld2.value) {
    error = "Not equal.";
    fld.style.background = "Yellow";
    fld2.style.background = "Yellow";
} else { ...