Navigation

Thursday 21 November 2013

Number type input fields validation using JQuery

Using JQuery it is easy to validate numeric data in input fields.

Below code validates numeric input in the input type fields.
For this we only need to add .number as class for the input html tags in which we need to validate numeric data.

$('input.number').blur(function () {

    var value = $(this).val();

    if (value == undefined || value == "") {
        $(this).parent().find("span").remove();
        return;
    }
    if (isNaN(value)) {
        $(this).parent().find("span").remove();
        $(this).parent().find("br").remove();
        $(this).parent().append("</br><span class='error'>Please Enter Number</span>");
    }
});

Above blur event shows the Please Enter Number error message just after user moves cursor from input field.



To validate the numeric data in any number of input fields on just need to add .number class to input tags and have to add below code in click event of submit button.

 
$('input.submitButton').click(function () {

    var errors = 0;
    $('div.Container table .number').each(function () {
        var value = $(this).val();
        if (isNaN(value)) {
            $(this).parent().find("span").remove();
            $(this).parent().find("br").remove();
            $(this).parent().append("</br><span class='error'>Please Enter Number</span>");
            errors += 1;
        }
    });
    if (errors > 0)
        return false;

});


No comments:

Post a Comment