I have one text box in which, user should enter only alphanumeric characters and non-text key presses should be allowed like backspace, arrow keys, etc . Also, it should also work on all major browsers (like Mozilla Firefox).
I have tried few examples which allowed to me enter only alphanumeric characters but backspace don't work with this below example in Mozilla Firefox.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
You can add [\b] to match and allow backspace.
Code:
var regex = new RegExp("^[a-zA-Z0-9\b]+$");
Demo: http://jsfiddle.net/M3bvN/
UPDATE
Instead of extend your regex you can check if the pressed key is in a list of allowed keys (arrows, home, del, canc) and if so skip the validation.
This not prevent the user to copy/paste not allowed characters. so perform the validation control in the blur event too (and always on server side).
Code:
var keyCode = event.keyCode || event.which
// Don't validate the input if below arrow, delete and backspace keys were pressed
if (keyCode == 8 || (keyCode >= 35 && keyCode <= 40)) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
return;
}
Demo: http://jsfiddle.net/M3bvN/3/
I was working on this for a bit, and this is what I came up with:
var input = $('input[name="whatever"]');
input.bind('keypress', function(e)
{
if ((e.which < 65 || e.which > 122) && (e.which < 48 || e.which > 57))
{
e.preventDefault();
}
});
It only allows numbers and letters, both upper- and lower-case. Note that it also disallows the space bar (that's what was needed for my application).
function lettersOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode == 8 || charCode == 46 || charCode == 37 || charCode == 39) {
return true;
} else if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
// alert("Enter letters only.");
return false;
}
return true;
}
$('.alphanumeric').bind('keypress', function (e) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
return ret;
});
This code will Firefox also
Related
I'm trying to regex an input field in javascript.
What I do is, eveytime a key is pressed, the following code is being called:
function testPattern(pattern, evt) {
// in this case, pattern = "^[0-9]*$"
var inputField = evt.getCurrentTarget();
var keyCode = evt.getKeyCode();
var oldValue = inputField.getSubmittedValue();
// return if keycode is navigation, delete or backspace
if((keyCode >= 35 && keyCode <= 40) || keyCode == 8 || keyCode == 46){
return;
}
var regExp = new RegExp(pattern);
var hasMatch = false;
hasMatch = regExp.test(String.fromCharCode(keyCode));
if (!hasMatch) {
inputField.setValue(oldValue);
evt.cancel();
}
}
The expected result is: no character is written in the input text box if the input is different from a digit.
It is working fine, except for the characters # $ % & and (
I've tried the following regex (very similar)
"^[\\d]$"
"^[\\d]*$"
"^[\\d]+$"
"^[0-9]*$"
Does someone know why this might be happening?
There is nothing wrong with your regexps.
The problem is in
// return if keycode is navigation, delete or backspace
if((keyCode >= 35 && keyCode <= 40) || keyCode == 8 || keyCode == 46)
return;
If you have a look at an ascii table you will see that:
8 backspace
35 #
36 $
37 %
38 &
39 ´
40 (
46 .
Your problem comes from a confusion between keyCode and charCode in the browser implement / keyboard event that you are listening to:
This question might be a good read: keycode and charcode
use the regex in this way:
/^\d+$/
Restrict this ASCII 35,36,37,38,39,40 to restrict those symbols or you can use below mentioned code.
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 32 && keyCode <= 32)||(keyCode >= 44 && keyCode <= 44)||(keyCode >= 46 && keyCode <= 46)||(keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
Good morning,
I facing a issue on the IE 10 where my keypress still can enter '%' but the FF and Chrome no such issue.
I found out that the key 37 is the [ left arrow ] which match with '%' in ASCII.
My sample code as below:
$('#refId').bind("keypress", function(event) {
// allow letters, numbers and keypad numbers ONLY
var key = event.charCode;
if((key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 97 && key <= 122)){
return true;
}
//allow backspace, tab, left arrows, right arrow, delete
key = event.keyCode;
if(key == 8 ||
key == 9 ||
key == 37 ||
key == 39 ||
key == 46){
return true;
}
return false;
});
Can give me some idea how to fix this?
Thanks.
-fsloke
Use var key = event.which; instead and join the if-statements.
The event.which property normalizes event.keyCode and event.charCode.
It is recommended to watch event.which for keyboard key input.
- https://api.jquery.com/event.which/
$('#refId').on("keydown", function(event) {
// allow letters, numbers and keypad numbers ONLY
var key = event.which;
if((key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 97 && key <= 122) ||
key == 8 ||
key == 9 ||
key == 37 ||
key == 39 ||
key == 46) {
return true;
}
return false;
});
I have implemented the below javascript method to restrict typing special characters except space, backspace, dot, hyphen and underscore but in a textbox and called this method in the onkeypress event of textbox.
The reason I have posted it here is it is working fine in laptop or pc but the validation is not working on tablet.
Can anyone tell me the reason for this?
function NoSpecialCharacters(evt) {
//this method allows alphabets numbers and some special
//characters like space, backspace, dot, hyphen and underscore
var keyCode = (evt.which) ? evt.which : event.keyCode
if ((keyCode >= 33 && keyCode <= 44) || keyCode == 47 || (keyCode >= 58 && keyCode <= 64) ||
(keyCode >= 123 && keyCode <= 126) || (keyCode >= 91 && keyCode <= 94) || keyCode == 96) {
return false;
}
return true;
}
I have to disable some symbols from html input.
e.which is not working properly on Firefox. Firefox disables backspace and ect.
Here is JS Fiddle:
var code = window.event ? event.keyCode : e.which;
event.keyCode works on firefox, but does not work with String.fromCharCode(code).
jQuery normalizes e.which, so you don't have to worry about this at all.
Also, it's a lot easier to just listen for the correct keycodes, there's no reason to convert the keycode to a character just to filter it out with indexOf ?
$('#foo').keydown(function(e) {
var code = e.which;
if (code == 8 || code == 13) return true; // backspace and enter
if (code < 48 || code > 57 || code == 188 || code == 190) return false;
});
FIDDLE
To keep most keys active, and just mainly disable characters, you could filter like this
$('#foo').keydown(function(e) {
var key = e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
key >= 48 && key <= 57 || // numbers
key >= 96 && key <= 105 || // Numeric keypad
key == 190 || key == 188 || key == 109 || key == 110 || // comma, period and minus, . on keypad
key == 8 || key == 9 || key == 13 || // Backspace and Tab and EnterEnd
key == 35 || key == 36 || // Home and
key == 37 || key == 39 || // left and right arrows
key == 46 || key == 45) // Del and Ins
return true;
return false;
});
FIDDLE
You've got two errors in your script:
you called the event parameter event but referred to e.which.
2. you have to call evt.preventDefault() for preventing the typed character to appear.
The latter point is wrong when adding jQuery event handlers. 'Normal' DOM handlers require preventDefault(), see also this comment.
→ jsFiddle
$('#foo').keypress(function(evt) {
var code = window.event ? event.keyCode : evt.which;
var chr = String.fromCharCode(code);
if ("0123456789.,".indexOf(chr) < 0) {
return false;
}
});
I'm validating my input field using key code to enter (a-z, A-Z, _). The javascript code looks something like this:
function checkForSpecialCharacters(event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if ((keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode == 9)
|| (keycode == 95)||(keycode == 8) || (keycode >= 97 && keycode <= 122)) {
return true;
}
else {
return false;
}
return true;
}
This works pretty fine in Chrome, IEs, but in firefox it prevents arrow key also.
I've gone through What are the ascii values of up down left right?. But In my case I need to prevent to enter all the special characters in input field.
The give solution in the above link does not fulfill my requirement.
Kindly reply with your positive response.
Thanks.
Got the solution of this problem. Just use event.which. Here which is a property of the event object. It contains the key code of the key which was pressed to trigger the event (eg: keydown, keyup etc.).
So just get the value fo the key pressed using event.which and check in if condition.
In my case in Firefox browser I was getting 0 for arrow keys. so I just added on more or condition like:
if ((keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode == 9)
|| (event.which == 0) || (keycode == 95)||(keycode == 8) || (keycode >= 97 && keycode <= 122)) {
return true;}
Hope it will help other pal.
Thanks