I need to restrict input of special characters (like “/”, “\”) as well as “$” (shift+4), “#”(shift+3), but also need to allow capital characters like “A” (shift+a), etc.
Below code works, but I am not restrict “$” and all (from “shift+0” to “shift+9”) as I’m allowing “shift”, Give me some response how to do that,
HTML
<input type="text" id="txtboxToFilter" />
Jquery
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#txtboxToFilter").keydown(function (event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// stop the keypress for special character "/", "\"
if (event.keyCode >= 190) {
event.preventDefault();
}
}
});
});
As mentioned in the comment, if you want to prevent the use of specific characters, you should attack the problem on the character level, and not try to restrict the use of specific keys. I would do something like in this fiddle. I am using a regular expression to replace all occurrences of unwanted characters. Because interrupting the user when typing is a bit odd, I used
change()which is triggered when the text field loses the focus.