Javascript limit text input characters - javascript

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;

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 ?

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>

Key code on firefox

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

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.

Categories