Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show form default Validation Status Programmatically

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(<a>) to send the form data using ajax. I also want to take advantage of HTML5 form validation capabilities.
So before sending the data, I used the function .checkValidity to check the validity of the form.
If it returns true then I send the data. But when it return false I want to show user that the form is invalid using HTML5 default notifying scheme. But I don't know how to trigger that.

Is there is any way to show the validation of the form programmatically.

One way to do is trigger the submit event if checkValidity return false. But this will refresh the page. I don't want to change the state of the page.

checkValidity only checks validity and inform the program. It doesn't inform the user interactively.

like image 682
Abhishek Gupta Avatar asked May 02 '26 06:05

Abhishek Gupta


2 Answers

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');

like image 191
Logemann Avatar answered May 04 '26 19:05

Logemann


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!

like image 30
e-motiv Avatar answered May 04 '26 19:05

e-motiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!