Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number validate at keypress

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();
        }
    });
});
like image 819
Dinesh Dinaz Avatar asked Dec 16 '13 08:12

Dinesh Dinaz


3 Answers

The first character is unrestricted because you have nested keypress handlers. Try this:

$('.Number').keypress(function (event) {
    var keycode = event.which;
    if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
        event.preventDefault();
    }
});
like image 93
Rory McCrossan Avatar answered Nov 16 '22 23:11

Rory McCrossan


Try

$('.Number').keyup(function (event) {
    var keycode = event.which;
    if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
        event.preventDefault();
    }
});
like image 39
Subin Jacob Avatar answered Nov 16 '22 21:11

Subin Jacob


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.

like image 1
Linsa Prajapati Avatar answered Nov 16 '22 21:11

Linsa Prajapati