简体   繁体   中英

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. 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?

Thanks in advance!!

You should listen for the submit event on the form. Then the HTML5 validators will stop the submit if there are validation errors.

$(".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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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