简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM