-1

I have this piece of code. According to keycodes here http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html

this code should work but for some reason I am getting these characters as true.

eiadfghcb.

 function validate(event) {
            var keycode =  event.keyCode; 
            if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
                return false;
            }
        }

html:

  <asp:TextBox ID="txtImp" runat="server" Height="23px" Width="80"  onkeypress="return validate(event)" onkeyup="calc()"/>
Akshay
  • 1,412
  • 2
  • 17
  • 51

2 Answers2

1

The following code should work for you:

function validate(event) {
    var code = event.code;

    if (typeof code !== "undefined") {
        var
            codeBeginning = code.substr(0, code.length - 1);

        if (code === "Period" || code === "NumpadDecimal" || code === "Backspace" || ((codeBeginning === "Digit" || codeBeginning === "Numpad") && !parseInt(code.substr(code.length - 1)).isNaN())) { // key pressed is one of the "."-keys, the "Backspace"-key or one of the number-keys.
            return true;
        }

        return false;
    }

    var keyCode = event.which || event.keyCode;

    if (keyCode === 8 || keyCode === 46 || (keyCode >= 48 && keyCode <= 57)) {
        return true;
    }

    return false;
}

Explanation regarding to why your code didn't work.

The first condition in your if-statement !(keycode == 8 || keycode == 46) will indeed evaluate to true when the key pressed is neither the decimal point-key or the BACKSPACE-key.

However the second and third condition will conflict with one another. This can be show by the following example:
The user presses the Numpad 2-key which (in my case) results in 50. This value does comply to the second condition as 50 is both higher than 48 and lower than 57, but it will not comply to the third condition as 50 is lower than 96.

As both the second and third condition will have to result to true and there is always one of the two that will result in false the code will never do what you intend it to do.

Disclaimer

My previous answer stated that KeyBoardEvent.keyCode is unreliable and resulted in an inability to capture the right keys on my machine.

Even though I'm now unable to reproduce this issue I would still advice you to only use KeyBoardEvent.keyCode when absolutely necessary (as the documentation of KeyBoardEvent.keyCode does state that it is implementation specific), and use KeyBoardEvent.which whenever possible.

Explaination regarding to why my code works.

As the KeyBoardEvent.keyCode relies heavily on the browser implementation thereof, I've chosen to using it as much as possible by instead using KeyBoardEvent.which.

However as both of these properties have become deprecated I've also used KeyBoardEvent.code to make sure that the solution adheres the lastest KeyBoardEvent specification.

As such my solution uses KeyBoardEvent.code when available as it isn't deprecated or implementation specific. If KeyBoardEvent.code is unavailable it uses KeyBoardEvent.which as it is more consistent that KeyBoardEvent.keyCode. And finally if KeyBoardEvent.which (as is the case in older browsers e.g. Internet Explorer 8) it will have to use KeyBoardEvent.keyCode.

  • Thanks a lot for this info. Never used charcode before. – Akshay May 01 '17 at 16:17
  • `(keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)` These do not conflict, as your answer states. They say: "The keycode is not between 48 and 57, and the keycode is not between 96 and 105." Though, I am curious... how did you know what OP wanted to do (*"it does what you want it to do"*) when they literally said nothing about what they wanted to do? – Tyler Roper May 01 '17 at 16:25
  • Additionally, switching `keyCode` to `charCode` isn't a resolve. Some browsers use `charCode`, others use `keyCode`. By switching them, you're just switching which browsers you want to support, but not supporting them all. In reality it should be `var keycode = event.keyCode || event.charCode` – Tyler Roper May 01 '17 at 16:31
  • (I apologize for the multiple comments, but I can't edit previous ones) - I just want to say one more thing, because this answer is full of misinformation: *"As stated in the note of the solution the key-codes for Flash don't match up with those of JavaScript. To fix this I've replaced the keyCode with charCode"* - `keyCode` has *nothing to do with Flash*. (Why would JavaScript have a method to look up Actionscript character codes...?) [This question](http://stackoverflow.com/questions/1444477/keycode-and-charcode) has a good outline of the differences between `charCode` and `keyCode`. – Tyler Roper May 01 '17 at 16:38
  • @Santi I've rewritten my solution so that it adheres to the lastest `KeyBoardEvent` specification and is as implementation independent as possible. I've also rewritten my explainations as clearly as possible to illustrate the problem the code that @Sak originally had. – DaftKauries May 01 '17 at 22:55
  • @DaftKauries Your new answer is well thought out and contains a lot of very useful information, very nice job. The only thing I'm still wondering... how did you know what OP wanted to achieve from his question (regarding num pad, period, backspace, etc)? – Tyler Roper May 02 '17 at 12:39
  • @Santi I based my interpretation around the key codes that he used in his example code and mapped those to the ones specified in the Flash documentation @Sak originally included. Based on that alone I had gathered that he wanted to validate the input so that it would allow any digit (whether entered on the numpad or not), a decimal point and of course allow the user to undo his mistake by using `BACKSPACE`. – DaftKauries May 02 '17 at 18:36
0

The issue:

Take a look at your third condition:

keycode < 96 || keycode > 105 //Where keycode is NOT between 96-105

Now look at the ASCII codes for the characters you entered:

a: 97
b: 98
c: 99
d: 100
e: 101
f: 102
g: 103
h: 104

It should now be obvious why your code is failing - You've included a condition that very specifically ignores the characters you're claiming "don't work".


keyCode vs charCode:

When it comes to keyCode, you're going to run into some cross-browser issues. For that reason you may want to consider checking both keyCode and/or charCode, as each works in a specific set of browsers. A simple way to be sure we're getting a value that's consistent is to do something like this:

var keycode = event.keyCode || event.charCode;

In the event that event.keyCode won't work, charCode will be used instead.


The solution:

If you simply want to ignore the condition that I pointed out as the problem, then just remove it:

if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
    return false;
}

That being said, your question doesn't say what your desire is... at all. It simply says that what you have "doesn't work for the characters mentioned".


Additional info:

As a side note, I'd be remiss if I didn't point out that your code is not exactly... friendly, for lack of a better word. An elegant way of resolving this is to replace condition lists with named functions, so the purpose and result is much more discernible, like so:

Bad:

if (sunny || not raining and warm || not(cloudy and raining) || not cold) 

Good:

if (weatherIsNice(...))

Applied in your case it may be something like

function characterIsAllowed(keycode) {
    if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
         return true;
    } else {
        return false;
    }
}

function validate(event) {
    var keycode = event.keyCode || event.charCode;
    if (characterIsAllowed(keycode)) {
        return false;
    }
}

Or, simplified one step further...

function characterIsAllowed(keycode) {
    return (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105))
}

function validate(event) {
    var keycode = event.keyCode || event.charCode;
    return !characterIsAllowed(keycode);
}
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • I have no idea what you *want* to do, and so I made no adjustments - my code will function exactly as yours already does. I just told you where your mistake is so that you can fix it. What were you trying to achieve with this: `keycode < 96 || keycode > 105`? Your question says "Why won't these characters work", but then you have a condition that says, specifically, *"don't allow these characters"* – Tyler Roper May 01 '17 at 16:18