简体   繁体   English

点击事件之前的HTML5表单验证

[英]HTML5 form validation before click event

I have the following form and input button: 我有以下表格和输入按钮:

 <form class="form-horizontal" role="form" id="category_markups_form" data-toggle="validator">
    {{#each context.category_0}}
      <div class="form-group">
        <label for="inputType" class="col-md-2 control-label" data-error="Please enter a number.">{{category_name}}</label>
        <div class="col-md-3">
            <input type="number" min="1.0" class="form-control" name="{{category_name}}" data-error="Please enter a number." required>
        </div>
      </div>
      {{/each}}
      <input id="to_subcategory_markups" type="submit" class="btn btn-success" value="Next: Subcategory Markups">
  </form>

My input button validates all of the inputs to make sure they are valid. 我的输入按钮会验证所有输入,以确保它们有效。 My button also calls a script to show another form if it is clicked: 如果单击该按钮,我的按钮还会调用一个脚本以显示另一个表单:

$("#to_subcategory_markups").click(function(e) {
    e.preventDefault();
    $("#subcategory_markups").show();
});

My problem is, as written, my other form will show if I click the input submit button WITHOUT validating all the inputs. 如我所写,我的问题是,如果我单击输入提交按钮而不验证所有输入,则会显示我的其他表单。 The only way to make sure the form validates is by removing my input's id attribute. 确保表单验证的唯一方法是删除输入的id属性。 But this means my click event would not fire. 但这意味着我的点击事件不会触发。 Is there a way I can make my form validate before firing off the click event? 有什么方法可以使我的表单在触发click事件之前进行验证?

Thanks in advance!! 提前致谢!!

You should listen for the submit event on the form. 您应该在表单上侦听submit事件。 Then the HTML5 validators will stop the submit if there are validation errors. 然后,如果有验证错误,HTML5验证器将停止提交。

$(".form-horizontal").submit(function(e) {
    e.preventDefault();
    $("#subcategory_markups").show();
});

please use this syntax to validate your form 请使用此语法来验证您的表单

$("#f").validate({
            rules: {
                field01: {
                    required: true
                },
                field02:{
                    required: true,
                },
                field03: {
                    required: true
                },
                field04: {
                    required: true,
                },
                field05: {
                    required: true
                }
            },
            submitHandler: function(form) {
                 form.submit(); //  or your action
             }
  });

here is f is your form id and field0* will be the name of your input fields that you want to be required. 这是f是您的表单ID,field0 *将是您需要的输入字段的名称。

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

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