在将字段设置为必填字段后仍然可以提交表单

Still able to submit form after setting field as mandatory

本文关键字:字段 提交 表单 设置      更新时间:2023-09-26

函数 假设用户是输入字段,然后单击"提交"按钮。所有字段都是必填字段。因此,如果用户不输入任何字段,他们将无法导航到下一页。

问题:

我已经将每个字段设置为"必需",但是,我仍然可以导航到下一页。这怎么可能,我找不到我到底做错了什么

代码:

 <form style=" alignment-adjust: autofocus" class="container" action="Page5" method="POST">
            Name: <input type="text" name="name" required><br><br>
            Email: <input type="text" name="email" required><br><br>   
            <input type="image" src="image/Submit.png" alt="Submit" width="250px" height="50px" onClick = "Page5()">
        </form>
<script>
        function Page5() {
            $("#page4").hide();
            $("#page5").show();
        }
    </script>

问题是浏览器只在表单提交时验证表单。因为您实际上并没有提交表单,而是使用javascript,所以浏览器不会显示任何错误消息。

一个可能的解决方案是这样的:

function Page5() {
    var $myForm = $('#myForm');
    // Check to see if the form is valid
    if ($myForm[0].checkValidity()) {
        // If the form is valid, go to the next page.
        $("#page4").hide();
        $("#page5").show();
    } else {
        // If the form is invalid, submit it. The form won't actually submit;
        // this will just cause the browser to display the native HTML5 error messages.
        $myForm.find('input[type=image]').click()
    }
}

来源。请注意,您需要在表单中添加id="myForm"或类似内容。

最后要记住的一件事是永远不要依赖javascript或浏览器验证,因为这很容易伪造。它应该只用于用户方便,您应该始终仔细检查服务器上的提交。

required属性在IE9或更早版本中不受支持,在Safari中也不受支持。因此,我建议您为这些浏览器创建自己的验证。否则,您的Page5()方法会出现问题。也许您正在使用它提交请求,因此它跳过了所需的属性验证。

在W3Schools 上阅读更多信息