Disable special characters entry in tablet - javascript

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;
}

Related

Javascript - Allow numbers, backspace, arrow keys and shift for selection

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 ?

Firefox compatible input filtering

I'm trying to prevent most special characters (with the exception of "_" and "-") from working on a text input field.
I started with doing a regex filter by pattern(didnt work), then by dynamic js, later to find out that it wouldn't work on firefox, I coudldn't use the dashes, underscores, backspace, delete, or arrow keys even though it showed I could on https://regexr.com/
I found another solution that actually prevented the keypress by using the ascii tables, sounded great as well but now I still can't use underscores or dashes though the my logic seems fine and the keys aren't logged.
<input id="directory" type="text">
$("#directory").keypress(function(e){
var keyCode = e.which;
/*
48-57 - (0-9)Numbers 65-90 - (A-Z) 97-122 - (a-z) 8 - (backspace)
*/
if (
!(
(keyCode == 8 )
||(keyCode == 45)
||(keyCode == 95)
||(keyCode >= 48 && keyCode <= 57)
||(keyCode >= 65 && keyCode <= 90)
||(keyCode >= 97 && keyCode <= 122)
)
){
e.preventDefault();
$("#directory").val('')
console.log(keyCode);
toastr.error("Your search string contains illegal characters. Please use, a-z, A-Z, 0-9, -, or _", "Error", {timeOut: 10000, preventDuplicates:true, positionClass : "toast-top-center"});
}
});
edit: the inverse of this didn't work either of course
if (
(
(keyCode >= 0 && keyCode <= 7)
||(keyCode >= 9 && keyCode <= 44)
||(keyCode >= 46 && keyCode <= 47)
||(keyCode >= 58 && keyCode <= 64)
||(keyCode >= 91 && keyCode <= 94)
||(keyCode == 96)
||(keyCode >= 123 && keyCode <= 127)
)
){
I'm not sure why, but 45 and 95 still wont let me enter underscores or dashes, can anyone help me, the solution I want is a-z, A-Z, 0-9, -, _ input?
I would suggest to not depend on keydown, as it will not fire when you paste content with the context menu (for example). To get an event fired for any change applied by the user, use the input event.
The downside of that event is that it cannot be cancelled. But it is not too difficult to undo the (part of the) change that has invalid characters in it.
Here is how it could work:
$('#directory').on('input', function (e) {
var i = $(this).val().search(/[^\w-]/);
if (i < 0) return; // All OK
$(this).val($(this).val().replace(/[^\w-]/g, ''));
this.setSelectionRange(i, i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="directory" type="text">
My opinion is that such blocking of characters is actually user-unfriendly: people might for a moment think their keyboard is malfunctioning. It is probably better to allow the characters to be typed, but to give a visual indication that the input is not valid, for example with a red border and an accompanying message.
It was a logic inversion issue ... all of the || allowed for characters you didn't want to "slip through". I removed the !() part and just returned from the event handler when an allowed key was typed:
var $output = $("#output")
$("#directory").keypress(function(e) {
var keyCode = e.charCode;
/*
48-57 - (0-9)Numbers 65-90 - (A-Z) 97-122 - (a-z) 8 - (backspace)
*/
if (
(keyCode == 8) ||
(keyCode == 45) ||
(keyCode == 95) ||
(keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 65 && keyCode <= 90) ||
(keyCode >= 97 && keyCode <= 122)
) return
e.preventDefault();
$("#directory").val('')
console.log(keyCode);
$output.text("Your search string contains illegal characters. Please use, a-z, A-Z, 0-9, -, or _");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="directory" type="text">
<pre id="output"></pre>

Javascript regex for numbers only is accepting # $ % & (

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>

Jquery to allow alphanumeric characters and non-text key presses

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

JavaScript - How to enable arrow key in Firefox browser while validating input fields against special characters

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

Categories