2
votes

I'm trying to use html5 validation and ajax.

The method checkValidity doesn't solve my problem, because it doesn't show the message error in the UI.

I need to launch the browser validation (and show error messages) using js. To do it I found that I have to submit the form and prevent the event. i.e:

$('form#x').submit(function(e){
   e.preventDefault();
   // ajax code
 });

This works ok and the ajax code is only executed if the all the form fileds are valid. However, I realized that once the form is valid, the ajax code is executed as many times as the submit button was clicked. WTF?

I could solve that issue by using a global flag:

flah = 0;
$form.submit(function(e){
    e.preventDefault();
    if(flag) return;
    flag = 1;
    //send x ajax
    // in ajax callback >> flag = 0 

});

Is there any other way to launch the validation without submit? Is the event-trigger problem a browser bug or is it a problem in my code?

Thanks

1

1 Answers

0
votes

try this:

$('form#x').submit(function(e){
   e.preventDefault();

    if(!this.checkValidity()){
       return false;
    }   

   // ajax code
 });