Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async html5 validation

For some reason html5 validation message is not shown when I'm using an async request.

Here you can see an example.

http://jsfiddle.net/E4mPG/10/

setTimeout(function() {                
  ...
  //this is not working
  target.setCustomValidity('failed!');                
  ...
}, 1000);

When checkbox is not checked, everything works as expected, but when it is checked, the message is not visible.

Can someone explain what should be done?

like image 424
denis_n Avatar asked Mar 17 '13 23:03

denis_n


1 Answers

I figured it out, turns out that the HTML5 validation messages will only popup when a form submit is in progress.

Here is the process behind my solution (when timeout is checked):

  1. Submits the form
  2. Sets the forceValidation flag
  3. Sets the timeout function
  4. When the timeout function is called, resubmit the form
  5. If the forceValidation flag is set, show the validation message

Basically perform two submits, the first one triggered by the button, and the second triggered when the timeout function is called.

jsFiddle

var lbl = $("#lbl");
var target = $("#id")[0];

var forceValidation = false;

$("form").submit(function(){
    return false;
});

$("button").click(function (){                
    var useTimeout = $("#chx").is(":checked");         

    lbl.text("processing...");
    lbl.removeClass("failed");
    target.setCustomValidity('');    
    showValidity();     

    if (forceValidation) {
        forceValidation = false;
        lbl.text("invalid!");
        lbl.addClass("failed");
        target.setCustomValidity('failed!');
        showValidity();
    } else if (useTimeout) {
        setTimeout(function () {
            forceValidation = true;
            $("button").click();
        }, 1000);
    } else {
        lbl.text("invalid without timeout!");
        lbl.addClass("failed");
        target.setCustomValidity('failed!');
        showValidity();            
    }
});

function showValidity() {                    
    $("#lbl2").text(target.checkValidity());
};

I am running on Chrome version 25.0.1364.172 m.

like image 77
Daniel Imms Avatar answered Oct 14 '22 21:10

Daniel Imms