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"/>
2
  • could you set up an example fiddle reproducing the issue? Note: why you use both event.keyCode and event.which? Commented Sep 25, 2012 at 7:20
  • jsfiddle.net/KMDVc it works fine on Chrome 21.0.1180.89 - I can't enter a dot Commented Sep 25, 2012 at 7:25

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

1

Modified your code here. it works in chrome.

Comments

0

You should use keydown event instead of keypress jsfiddle

Comments

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('')
    }
});

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.