Tuesday, December 20, 2011

HTML5 Custom Form Validation with Ajax

It is fairly easy to create HTML5 form validation with non-ajax. But I found out that form validation with ajax is bit tricky. If anyone knows better way please let me know.

The problem was when to call setCustomValidity(). I had to call it inside of onclick event handler which runs just before form submission.

So, when you click on submit button, onclick is fired and initValidation() is called. The method checks whether input is equals to the string "tt". If so it will set custom error message (i.e. setCustomValidity() )

You have to make sure to kill the submit by event.preventDefault()

NOTE: I tried this without using onclick. I put form validation code inside of submit() but setCustomValidation() is called too late there thus error popup didn't show up. (if you click submit one more time, it will show the popup.)

CODE:


Test1: Test2:


$(document).ready(function() {
    $("#myForm").submit(function(event) {
        event.preventDefault(); //cancel submit
        
        //your ajax code here...
    })
});

function initValidation() {
    var mtxt = document.getElementById("myText");
    mtxt.setCustomValidity(""); //reset
    
    if($("#myText").val() == "tt") {
        mtxt.setCustomValidity("this is my custom error message");
    }
}


No comments:

Post a Comment