Show form default Validation Status Programmatically

后端 未结 2 1011
孤街浪徒
孤街浪徒 2020-12-21 06:23

I want to submit a form using ajax. So I am not using the type=submit. I am using a onClick event on a link() to send the for

相关标签:
2条回答
  • 2020-12-21 07:08

    You can do it if you let your form have a submit button and return false! And you cán do it in the same event handler as the non-submits! So, first test if you are part of a form and if so, make it check Validity and never return true (even if valid)!

    $('.ajx')   
        .on("submit click", function(e) {
    
            var $this           = $(this)
    
            //Force native form validating and notification
            form = $this.closest('form')[0]
            if (form) {
                //Follow through with form submit (element must be of submit type!)
                if(!form.checkValidity()) {
                    //don't ask me!
                    sleep(3000);
                    return false
                }
            }           
    
            //only preventDEfault AFTER possible form element click
            e.preventDefault()
    
            //...your project further ajax code
            //Makes sure your form never submits
            if (e.type=='submit') return false
    }
    

    Small downside: You have to do this on the submit button, but it's always possible to change your <a> into type=submit. You don't have to change the non form <a>'s though!

    0 讨论(0)
  • 2020-12-21 07:17

    We have exactly the same problem and we tried very different things and a lot of them were hacks like pseudo submits and event.preventDefault() approaches. All in all i must say that HTML5 validation is nice in general but really bad in practice because its not possible to display backend validation errors the same way as frontend validation errors.

    And only god knows why the HTML5 folks didnt thought about a simple API where we can trigger the validation like this element.triggerValidationMessage('my message');

    0 讨论(0)
提交回复
热议问题