经过javascript验证后,即使存在错误,也会执行该功能

时间:2019-05-07 16:57:17

标签: javascript

我可以使用javascript验证我的表单,但是即使表单数据无效,也要对“提交”按钮进行下一个处理。只有在javascript验证后我的表单中没有错误时,我才能阻止该页面加载支持该页面的其他页面

script type="text/javascript">
function matchpass(){ 

    var firstpassword=document.myform.psw.value;
    var secondpassword=document.myform.pswrepeat.value;  
    var x=document.myform.email.value;  
    var atposition=x.indexOf("@");  
    var dotposition=x.lastIndexOf(".");  

    if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
    {  
          alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
          return false;  
    } 

        if(firstpassword==secondpassword)
        {  
            return true;  
        }  
        else
        {  
            alert("password must be same!");  
        return false;  
        }  

    }

</script>
</head>
<body>
</div>

    <form name="myform"  action="RegisterControllerServlet" method="post"  >

    <input type="hidden" name="command" value="ADD">

  <div class="container">

    <p>Please fill in this form to create an account.</p>
    <hr>

     <label for="email"><b>Enter your Employee id</b></label>
    <input type="text"  name="de_eid"  >


    <label for="email"><b>Email</b></label>
    <input type="text"  name="email">

      <Select name="is" class="custom-select" style="width:500px; background-color: #A0A0A0; height:40px;">
    <option value="">Choose Occupation</option>
    <option value="Doctor">Doctor</option>
  <option value="Receptionist">Receptionist</option>
  <option value="labassistant">Lab assistant</option>
  <option value="pharmacist">Pharmacist</option>
    </Select>

    <br><br>
    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>

    <label for="psw-repeat"><b>Repeat Password</b></label>
    <input type="password" placeholder="Repeat Password" name="pswrepeat" required>
    <hr>


    <button type="submit" class="registerbtn" onclick="matchpass();">Register</button>
  </div>

我希望页面仅在验证中没有错误时才将用户重定向到应该加载的页面

1 个答案:

答案 0 :(得分:0)

您的<form>标签应具有onsubmit属性,而不是底部的<button>的{​​{1}}。

onclick