【问题标题】:Validate all form data before submitting在提交之前验证所有表单数据
【发布时间】:2016-09-03 04:34:14
【问题描述】:

我在 HTML 中创建了一个表单,并在每个字段上都使用了 onblur 事件,它工作得很好。问题是当我单击提交按钮(它将数据发送到 servlet)时,即使数据无效,也会提交数据。这是一个例子。

<html>
<head>
<script>
function check()
{
    if(checkName()==true)
        return true;
    else{
        alert('vhvh');
        return false;
    }
}
function checkName()  
{   
    var uname=document.enq.Name.value;
    var letters = /^[A-Za-z, ]+$/;  
    if(uname.match(letters))  
    {   
        document.getElementById('Name').style.borderColor = "black";
        return true;
    }  
    else  
    {  
        document.getElementById('Name').style.borderColor = "red";
        //alert('Username must have alphabet characters only');  
        //uname.focus();  
        return false;
    }  
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit"> 
</form>
</body>
</html>

我该如何解决这个问题?

【问题讨论】:

    标签: javascript html forms servlets


    【解决方案1】:

    使用

    &lt;input class="button" type="button"&gt;

    并像这样放置一个 onclick 事件:

    &lt;input class="button" type="button" onclick="this.submit()"&gt;

    这样您就可以在提交数据之前对其进行操作。

    【讨论】:

      【解决方案2】:

      有一个“onsubmit”事件允许您控制表单提交。使用它来调用您的验证函数,然后才决定是否要允许用户提交表单。 http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html

      如果你想让它阻止表单提交,你必须按以下方式使用它:

      <form onsubmit="return check()">
      

      【讨论】:

      • 感谢@Ni。现在我创建了一个函数来检查数据是否有效并且运行良好。但我仍然如何限制它向 servlet 提交数据。这是我的新方法的代码。 function check() { if(checkName()==true && checkNumber()==true && ValidateEmail()==true) alert('true');否则警报('假'); }
      • @ParveenKumar 如果函数返回false,则不会提交表单。
      • @ParveenKumar 我将答案中的链接更改为更好的网站
      • 这不是工作,即使返回 false 它正在提交数据。
      • 请将新代码添加到您的问题中,以便我提供帮助
      猜你喜欢
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多