1

I use the following function for integer validation on keydown event.now i need to allow comma and space bar within this .how to do this?

function intValidate(event) {
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||(event.keyCode == 65 && event.ctrlKey === true) ||(event.keyCode >= 35 && event.keyCode <= 39))
        {
            return;
        }
    else 
    {
        if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )&&event.keyCode < 188)
        {
            event.preventDefault(); 
        }   
    }
  }
1
  • Search for the relative keyCode and use them in your conditions. Commented Sep 7, 2012 at 7:12

4 Answers 4

3

Check for the key codes 188 and 32, respectively. Whereas 188 is "comma", you may also want to check for 110 – "decimal point", for the character on your numpad (depending on keyboard layout, of course).

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

1 Comment

sorry, I got the comma and period key codes mixed up first. see my update
1

Add the Keycodes for the new Chars you need to allow in your If statement. tr this Keycodes List

Comments

0

32 will be for Space.

188 will be for Comma(,).

So Add it in your if condition:

event.keyCode == 32 || event.keyCode == 188

See the whole list: KeyCode List

Comments

0

You can call this function:

var isValid = function(key) {

    var allowedCharacters = ['0','1','2','3','4','5','6','7','8','9',' ', ',']
    if (allowedCharacters.contains(key)) return true;
    return false;

};

Here is a fiddle: http://jsfiddle.net/Js9wQ/

2 Comments

How would you implement that in a keydown listener?
var key = String.fromCharCode(e.keyCode);

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.