Number validate at keypress

Viewed 42132

I validate the phone number using below code its working fine but i allow char at first time while user entering the values. how i can solve it. . . .

$('.Number').keypress(function () {
    $('.Number').keypress(function (event) {
        var keycode;

        keycode = event.keyCode ? event.keyCode : event.which;

        if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 ||
                keycode == 37 ||keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
            event.preventDefault();
        }
    });
});
5 Answers

Here is a function that will validate the input. It will return true if the value is a number, false otherwise. Numbers are charcode 48 - 57. This function also allows all control characters to return true. (<32)

function isNumber(evt)
{
   evt = (evt) ? evt : window.event;
   var charCode = (evt.which) ? evt.which : evt.keyCode;
   if (charCode > 32 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
}

Here is a chart of the codes.

This is the simplest solution for KeyPress Number Events:

 $(document).ready(function(){    
    $(".Number").keypress(function(event){
        var keycode = event.which;
        if (!(keycode >= 48 && keycode <= 57)) {
            event.preventDefault();
        }
    });
 });

Related