Firefox compatible input filtering - javascript

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>

Related

Restrict entering Spaces in TextBox in Javascript

In my code have to allow numerical alphabets and special characters. but in my code not accepting the space and special characters except #.
Here is my code.
allowAlphaNumericSpace(e: any) {
var code = 'charCode' in e ? e.charCode : e.keyCode;
if (
!(code > 47 && code < 58) && // numeric (0-9)
!(code >= 64 && code <= 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)
) {
// lower alpha (a-z)
e.preventDefault();
}
}
charCode is non-standard, deprecated, and not foreseen for keydown events, it may be available, but always 0.
keyCode is also deprecated.
Use e.key:
const accepted = " ,;!?";
function allowAlphaNumericSpace(e) {
var code = e.key;
if (isNaN(code) && code.toUpperCase() == code.toLowerCase()
&& !accepted.includes(code)) {
e.preventDefault();
}
}
document.querySelector("input").addEventListener("keydown", allowAlphaNumericSpace);
<input>
If some other characters need to be accepted, it is easily adapted.

Disable special characters entry in tablet

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

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

How to prevent users from entering invalid characters inside an input field

Given a text input field. How can I prevent users from entering spaces, and other other than letters numbers or dashes (-).
Alphanumerics only - "The alphanumeric character set consists of the numbers 0 to 9 and letters A to Z. In the perl programming language, the underscore character ( _ ) is also considered to be a member of the alphanumeric set of characters"
This is for a field where users can pick a custom url. I would like to prevent users from entering invalid characters.
Ideas? Thanks
You can do this using the jQuery keyup(..) method. You will want to check that the event.keyCode is something valid. If it is not valid, you can prevent the event with preventDefault().
Remember to validate the data sent to the server because anything you do in javascript can be subverted.
Here is a library to do it for you: http://www.itgroup.com.ph/alphanumeric/
DEMO - JS Fiddle Link
Sorry for the late response. Though my answer is late. I have modified few changes to the answer and here it goes.
Validation Required
Restrict Digits entering on initial
Restrict Spaces, special characters but allow backspace and delete
Enable Alpha Numeric Characters
<input name="pac_code" id="input_8_6" type="text" value="" class="form-control medium pacerror pacvalid" data-rule-maxlength="9" data-rule-minlength="9" maxlength="9" minlength="9" placeholder="Porting authorisation code (PAC) *" data-rule-required="true"
autocomplete="off" size="9">
<label for="input_8_6" style="color: #ff0000;font-weight: 300;font-size: 12px;margin-bottom: 1%;">Example: ABC123456</label><br />
<label class="PAC_error error" style="display:none;">Invalid PAC Format</label>
</div>
JQuery
jQuery(document).ready(function() {
$('#input_8_6').bind('keypress', function(event) {
var regex = new RegExp("^[a-zA-Z0-9\b]+$");
var regchar = new RegExp("^[a-zA-Z\b]+$");
var regnum = new RegExp("^[0-9\b]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
var pacvalue = $(this).val().length;
if (!regex.test(key)) {
event.preventDefault();
return false;
} else if (pacvalue <= 2) {
for (i = 0; i <= 2; i++) {
if (!regchar.test(key)) {
event.preventDefault();
return false;
}
}
} else if (pacvalue >= 3) {
for (j = 4; j <= 9; j++) {
if (!regnum.test(key)) {
event.preventDefault();
return false;
}
}
} else {
return true;
}
});
});
There are plenty of Javascript validation libraries out there. A quick Google search for 'javascript validation' produced the JQuery Validation plugin plugin as the first hit, so that's probably a good place to start.
As #Chris Cooper said, make sure that you also do server-side validation, because it's pretty trivial for a user to turn off javascript and avoid your client-side validation rules.
Though my answer is very late, but this may help for further readers/techie's.
Who wants to implement a textbox to accepts with below condition.
should accept Alphabets.
should accept Numbers.
should not accept any special characters.
Below is the code.
$("input[name='txtExample'] ").focus(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
}).keyup(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
}).keypress(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtExample"/>
added with example.

Javascript limit text input characters

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;

Categories