Showing posts with label custom form validation. Show all posts
Showing posts with label custom form validation. Show all posts

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");
    }
}


Sunday, December 18, 2011

Custom form validation with HTML5!

I know there are many HTML5 form validation on the web but I made my own test demo so let me share.

The important thing is I wanted to create my own custom validation rule and custom error message.

I have 2 input text fields. Left field value has to be smaller than right field value. (like to-from date if u will)
Then my javascript compare each value and triggers custom validation error.

Note that you must remember to put empty string in setCustomValidity() otherwise after error is thrown, second time input will still cause custom error message to be shown.

For more detail about custom validation, check out: http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-setcustomvalidity



Custom: less: <= more:

Code:




  
Custom: less: <= more: