简体   繁体   English

表单验证HTML5

[英]Form validation HTML5

I am using the 'required' attribute in my form child tags for validation. 我在表单子标签中使用“ required”属性进行验证。 The problem that I have is that, when I first click submit, no validation takes place and an empty form also gets submitted. 我的问题是,当我第一次单击提交时,没有进行任何验证,并且还提交了一个空表格。

From the second time on wards, each time I click submit the validation check kicks in and reports an empty field. 从第二次开始,每次单击提交时,都会启动验证检查并报告一个空字段。

My code: 我的代码:

<form>
    <label for="id">ID:</label>
    <input type="text" class="form-control"  id="id" required>
    <label for="name">Name:</label>
    <input type="text" class="form-control" id="name" required />
    <button type="submit" class="btn btn-info pull-right"   id="sub">Submit</button>
</form>

POST request: POST请求:

$("#sub").click(function(){
    var sendf = {
        id: $("#id").val(),                             
        name: $("#name").val()
    };
    $.ajax({
        type: "POST",
        url: "",
        data: sendf,
        dataType: "text",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function(response, status, xhr) {                                                             

        },
    }); //ajax ends
    event.preventDefault();
    $(this).unbind();
});//sub click ends

Am I doing anything wrong? 我做错什么了吗? On button click, its just a simple POST request that takes place. 单击按钮,它只是发生一个简单的POST请求。 Any help is appreciated. 任何帮助表示赞赏。 Thanks ! 谢谢 !

The problem is you are intercepting the click action on the button - so the html form validation never takes place and the POST will process happily because you never check that the form is valid before sending it. 问题是您正在拦截按钮上的click操作-因此html表单验证不会发生,并且POST将愉快地处理,因为您在发送表单之前从未检查过该表单是否有效。

It works fine the second time because after the first click you have unbound your click handler and the form submits using a regular form submit event - resulting in the page reloading as it is no longer being handled by the AJAX request (in the now unbound click handler). 第二次工作正常,因为在第一次单击后,您取消了单击处理程序的绑定,并且使用常规的表单提交事件提交了表单-导致页面重新加载,因为它不再由AJAX请求处理(在现在未绑定的单击中)处理程序)。

If you instead bind your function to the form's submit event, the browser will run the HTML form validation first, before calling your event handler. 如果您将函数绑定到表单的Submit事件,则浏览器在调用事件处理程序之前首先运行HTML表单验证。 If you remove the $(this).unbind(); 如果删除$(this).unbind(); you will continue to submit the form via AJAX and not with a page reload. 您将继续通过AJAX提交表单,而不会重新加载页面。

use this code ( jsFiddle demo ): 使用以下代码( jsFiddle演示 ):

$("form").on("submit", function(ev){
    ev.preventDefault(); //prevent regular form submission via a page reload

    var sendf = {
      id: $("#id").val(),                             
      name: $("#name").val()
    };

    $.ajax({
           type: "POST",
           url: "https://httpbin.org/post",
           data: sendf,
           dataType: "text",
            headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function(response, status, xhr) {                                                             
                console.log(response);
            },

        }); //ajax ends
});//sub click ends

If you do want to disable submitting the form more than once, see this question . 如果您确实想多次禁用提交表单,请参阅此问题

Is there any javascript being executed on it? 是否正在执行任何JavaScript? Because when I import this HTML into a codepen, the required works as expected... 因为当我将此HTML导入到Codepen中时,所需的功能可以按预期工作...

Edit 编辑

The event.preventDefault(); event.preventDefault(); is preventing the default behaviour of the "required". 防止“必需”的默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM