Validate input value before it is shown to user

0 votes
81 views
asked Jun 21, 2013 in HTML by john (4,220 points)

I have an html <input> and some pattern (e.g. -?\d*\.?\d* float-signed value).
I should prevent typing the not matched value.

1 Answer

0 votes
answered Jun 21, 2013 by kalpana (3,995 points)

Try this code:


 jQuery.fn.numeric = function (pattern)
{
    $(this).keypress(function(e)
    {
         var sChar = String.fromCharCode(!e.charCode ? e.which : event.charCode);
        e.preventDefault();
        var sPrev = $(this).val();
        if(!pattern.test(sChar)){
            return false;
        } else {
            sPrev = sPrev + sChar;
        }

        $(this).val(sPrev);

    });

};

$("#validateId").numeric(/^-?\d*\.?\d*$/);

jsfiddle.net/aBNtH/

...