Stopping Characters From Being Entered In Form Field - javascript

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>

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>

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

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