Javascript不会与HTML代码

时间:2017-07-25 13:56:17

标签: javascript java html jsp

代码用JSP编写,应验证密码并确认密码正确性,然后将提交事件继续到Java servlet。但问题是,如果验证脚本失败,它将不会显示警报消息,也不会关注密码输入。我使用了chrome,explorer和Eclipse默认浏览器..只是不起作用

function validate(event){
  event.preventDefault();
  var pattern = /^(?=.*[a-z].*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,32}$/;
  var pwd = document.form.password.value;
  var confPwd = document.fomr.confPass.value;
  if(pwd.match(pattern)){
	  alert("Password must be between 8 to 32 characters,\n have at least one digit \n two lower and one upper case letters.");
    document.form.password.focus();
    return false;
  }else if(pwd == confPwd){
    alert("Passwords do not match. Please try again.");
    document.form.password.focus();
    document.form.confPass.focus();
    return false;
  }else{
    document.form.submit();
  }
 }
<form name="form" method="post" action="RegisterPath" onSubmit="return validate(event);">
  <table class="box">
    <tr>
      <td class="left">Password:</td>
      <td><input type="password" name="password" placeholder="Enter password" required/></td>
    </tr>
    <tr>
      <td class="left">Confirm Password:</td>
    	<td><input type="password" name="confPass" placeholder="Re-enter password" required/></td>
    </tr>
  </table>
</form>

1 个答案:

答案 0 :(得分:-1)

此工作代码将为您提供帮助。

function validate(event) {
  event.preventDefault();
  var pattern = /^(?=.*[a-z].*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,32}$/;
  var pwd = document.form.password.value;
  var confPwd = document.form.confPass.value;
  if (!pwd.match(pattern)) {
    alert("Password must be between 8 to 32 characters,\n have at least one digit \n two lower and one upper case letters.");
    document.form.password.focus();
    return false;
  } else if (pwd != confPwd) {
    alert("Passwords do not match. Please try again.");
    document.form.password.focus();
    document.form.confPass.focus();
    return false;
  } else {
    document.form.submit();
  }
}
<form name="form" method="post" action="RegisterPath" onsubmit="return validate(event);">
  <table class="box">
    <tr>
      <td class="left">Password:</td>
      <td><input type="password" name="password" placeholder="Enter password" required /></td>
    </tr>
    <tr>
      <td class="left">Confirm Password:</td>
      <td><input type="password" name="confPass" placeholder="Re-enter password" required /></td>
    </tr>
    <tr>
      <td colspan="2"><button type="submit">Submit</button></td>
    </tr>
  </table>
</form>