In textbox, I only want to allow numbers, backspace, left and right arrow keys and shift + arrow keys(for selection) to get typed and block typing of alphabets and special characters.
Tried using following code:
var key = e.which || this.value.substr(-1).charCodeAt(0);
key = String.fromCharCode(key);
var regex = /^[0-9\b]+$/;
With Regex:
if(!regex.test(key) && !(e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)) && e.keyCode!=37 && e.keyCode!=39)
return false;
Above code blocks typing of alphabets but allows special characters.
Without Regex:
if((e.shiftKey && e.keyCode > 48 && e.keyCode < 57) || (e.keyCode <= 48 && e.keyCode >= 57) || (e.keyCode <=96 && e.keyCode >=105))
return false;
But in above code user can see characters getting typed and removed.
I want to block typing of alphabets and special characters. Can anyone correct my code ?
Related
I want to restrict all symbols from being entered into my form fields in html.
Here is my code...
<script>
$('#location').keypress(function (e) {
var regex = new RegExp("[^a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
</script>
But that code does not allow any spaces or even using the delete key. I want everything to work but don't want any symbols (ie. $##%^!'"[]{}() etc...)
You could remove the invalid characters on keyup instead.
$('#location').keyup(function(e){
$(this).val($(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
});
Otherwise you have to specify the keyCode of the keys you want to allow.
http://www.asciitable.com/
Just get the range of letters and numbers.
48 - 57 (0-9)
65 - 90 (A-Z)
97 - 122 (a-z)
<script>
$('#location').bind('keypress', function (e) {
if (e.which < 48 ||
(e.which > 57 && e.which < 65) ||
(e.which > 90 && e.which < 97) ||
e.which > 122) {
e.preventDefault();
}
});
</script>
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 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
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
I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).
EDIT - Added code
<input type="text" onkeypress="return checkInput();">
function checkInput(){
return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
}
Just change the regex in the example to something like this:
numcheck = /[^a-z0-9_-]/;
Or better yet, avoid the double negative with:
numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);
Then you can look up the keycodes of backspace, etc. and check for them too:
if (keychar === 8) return true;
...
Or even put them in your regex:
numcheck = /[a-z0-9_\x08-]/;
You haven't provided any code samples, so it's hard to be specific in a response, but as a general strategy, try this: instead of trying to whitelist characters that can be input while they are being typed in, validate the contents of the text box after every key stroke to make sure that it still contains valid characters. If it doesn't, remove the last character entered.
This approach will allow special keys like backspace, etc., while at the same time achieve what it sounds like you are really after: a valid value in the text box.
Yes you can limit the input of characters. For example create a function that checks what is going on, return true if everything is OK and false if not:
// return true for 1234567890A-Za-z - _
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (e.which == 45 || e.which == 95 || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122))
return true;
return false;
}
return true;
}
once you have the function, hook it into you input (this is with jQuery):
$('#InputID').keypress(InputCheck);
You can make as complicated a check as you want, for example this will allow for USD money values:
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46 && e.which != 36) {
return false;
}
// . = 46
// $ = 36
var text = $(this).val();
// Dollar sign first char only
if (e.which == 36 && text.length != 0) {
return false;
}
// Only one decimal point
if (e.which == 46 && text.indexOf('.') != -1) {
return false;
}
// Only 2 numbers after decimal
if (text.indexOf('.') != -1 && (text.length - text.indexOf('.')) > 2) {
return false;
}
return true;
}
You can press any key you like, as long as you keep the value from including anything
not in the white-list.
inputelement.onkeyup=function(e){
e=e || window.event;
var who=e.target || e.srcElement;
who.value= who.value.replace(/[^\w-]+/g,'');
}
Add this code to onkeypress event.
var code;
document.all ? code = e.keyCode : code = e.which;
return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));
For browser compatibility, You can add
var k = e.keyCode == 0 ? e.charCode : e.keyCode;