0

I use the following java script function for integer validation.it was work fine in FireFox.But in IE and Chrome (not Fire Fox)allow the dot(.) symbol in that textbox.How to control do not appear the dot(.) symbol in text box while using IE and Chrome?

javascript function

$('.intValidate').live('keypress', function(event) {
    if((event.keyCode != 8)&&(event.keyCode != 9)&&(event.keyCode != 37)&&(event.keyCode != 39)&&(event.keyCode != 46)&&(event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});

I use the class like,

<input type="text" id="abcd" style="width:30px" maxlength="2" class="intValidate"/>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
User
  • 1,644
  • 10
  • 40
  • 64

5 Answers5

1

i dont think integer validation using event key codes is a viable option, i recommend you to use regex or if you really want to block using only the above way, you can also block for keyCode 110 - look here for complete event codes

http://www.webonweboff.com/tips/js/event_key_codes.aspx

and

http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html for your regex validations

danwellman
  • 9,068
  • 8
  • 60
  • 88
1

Modified your code here. it works in chrome.

0

You should use keydown event instead of keypress jsfiddle

Anoop
  • 23,044
  • 10
  • 62
  • 76
0

You could also do something like this:

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
$('.intValidate').live('keyup', function(event) {
    var $this = $(this);
    if (isNumber($this.val())) {
        $this.val(Math.floor($this.val()));
    } else {
        $this.val('')
    }
});
Miha Rekar
  • 1,237
  • 12
  • 15
0

First of all, you shouldn't do validation upon typing, as in key presses, instead, you should do validation on the value change of the text area where you are inputting the text. This is so because:

  • different keyboards may send different characters with the same key code.

  • besides regular typing, every system has IME modes, some ways to insert characters by their Unicode codepoints, by copying and pasting and so on.

By validating the text after the control has changed will spare you the trouble of finding out how the text was inserted.

Here's a similar example: How to impose maxlength on textArea in HTML using JavaScript

Community
  • 1
  • 1