Restrict entering Spaces in TextBox in Javascript - 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.

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>

Stopping Characters From Being Entered In Form Field

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>

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