Reputation: 967
I'm validating text-boxes such that they can contain letters,numbers, and these special characters only: ` , - . ' ~
I'm using the Jquery 'key-down' event for this. If the user enters an invalid character,I prevent it from showing up in the textbox. For the enabling just the tilde, and disabling the other special characters, I'm supposed to detect if the shift key is held down. I've used a Boolean variable for this.
Problem is it's allowing the other special characters like !, $, to be typed in.It isn't going inside the isShiftPressed == true
condition in ValidateKeyDown
. I had put an alert inside it, which didn't execute.
So this is my code:
$.fn.ValidateKeyDown = function () {
return this.each(function () {
$(this).keydown(function (e) {
if (e.shiftKey) {
isShiftPressed = true;
return;
}
else if (isShiftPressed == false) {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 9) // Tab
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 65 && n <= 90) // alphabets
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105) // number on keypad
|| (n == 109) //(- on Num keys)
|| (n == 189) || (n == 190) || (n == 222) || (n == 192) //hypen,period,apostrophe,backtick
)
) {
e.preventDefault(); // Prevent character input
return false;
}
}
else if (isShiftPressed == true) {
var n = e.keyCode;
if (n != 192) {
e.preventDefault(); // Prevent character input
return false;
}
}
return true;
});
});
};
$.fn.ValidateKeyUp = function () {
return this.each(function () {
$(this).keyup(function (e) {
if (e.shiftKey) {
isShiftPressed = false;
}
});
});
};
Upvotes: 0
Views: 634
Reputation: 1078
e.shiftKey itself tells you whether shift is pressed so you could directly use that. You don't need a separate variable to track that.
$.fn.ValidateKeyDown = function () { return this.each(function () { if (!e.shiftKey) { ... } else { ... } }
Upvotes: 1
Reputation: 9528
I noticed that e.shiftKey only returns true on key up and hence isShiftPressed is always false. Try this instead
$.fn.ValidateInput = function () {
return this.each(function () {
$(this).keydown(function (e) {
var n = e.keyCode;
if (n == 16) {
isShiftPressed = true;
return;
}
if (!isShiftPressed) {
if (!((n == 8) // backspace
|| (n == 9) // Tab
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 65 && n <= 90) // alphabets
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105) // number on keypad
|| (n == 109) //(- on Num keys)
|| (n == 189) || (n == 190) || (n == 222) || (n == 192) //hypen,period,apostrophe,backtick
)) {
e.preventDefault(); // Prevent character input
return false;
}
}
else if (isShiftPressed) {
if (n != 192) {
e.preventDefault(); // Prevent character input
return false;
}
}
return true;
})
.keyup(function (e) {
if (e.keyCode == 16) {
isShiftPressed = false;
}
});
});
};
Note: I also combined ValidateKeyup and ValidateKeydown, but that shouldn't matter.
Upvotes: 1