How to force form client-side validation in or before $.ajax()

后端 未结 4 1802
难免孤独
难免孤独 2020-12-19 00:34

I have a form and unobtrusive validations are enabled. By default in submit method client side validation gets triggered and (if you have any errors) the form looks like thi

相关标签:
4条回答
  • 2020-12-19 00:58

    You must force the form to validate before checking if it is valid. Something like this:

    var form = $( "#myform" );
    form.validate();
    if (form.valid()) {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-19 01:01

    I did...

    $("#form-submit-button").click(function (e) {
        e.preventDefault(); // Stops the form automatically submitting
        if ($("#my-form").valid()) {
            $("#my-form").submit();
        }
    });
    

    This also seems to be a good solution if you have say textboxes with a plugin to make those textboxes into a calendar control. Only reason I say this is because I used Zebra Datepicker with an MVC form and it would submit an invalid form if focus was on the calendar date picker. Using the below code stops this.

    0 讨论(0)
  • 2020-12-19 01:09

    I was having the same issue Yablargo was having in that it was saying that valid is not a function, so I came up with this:

    For the onclick handler of the submit button, I put this:

    onclick="return $(this).closest('form').checkValidity();"

    0 讨论(0)
  • 2020-12-19 01:10

    Oh...

    if (form.valid()) // do submit
    
    0 讨论(0)
提交回复
热议问题