Allow AlphaNumeric and other symbol using JavaScript - javascript

I have use this code for allow numeric only in textbox, but how make Charkey only allow AlphaNumeric and other symbol like -./ (dash,dot,slash)
this my code for allow Numeric
function NumericKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
thankyou

Firstly, Character Codes and Key Codes are different thing, what you're looking for is Key Codes.
You can first check the key codes you want to allow/disallow by looking them up in a online table, or here: http://keycode.info/
Then then by using a whitelist/blacklist to check the codes:
function NumericKey(evt){
var allowed = [189, 190, 191]; // corresponds to **. , -**
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return allowed.indexOf(charCode) >= 0;
return true;
}
This would allow you to arbitrarily whitelist any keycodes.
A simpler solution to your case, since key codes of ,.- are adjacent to each other:
function NumericKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode >= 189 && charCode <= 191))
return false;
return true;
}

You should not listen for keyboard events (keydown / keypress / keyup) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.
Moreover, that won't work on mobile, where most keys emit the same values e.key = 'Unidentified', e.which== 229 and e.keyCode = 229.
Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:
const input = document.getElementById('input');
input.oninput = (e) => {
const cursorPosition = input.selectionStart - 1;
const hasInvalidCharacters = input.value.match(/[^0-9 -./]/);
if (!hasInvalidCharacters) return;
// Replace all non-digits:
input.value = input.value.replace(/[^0-9 -./]/g, '');
// Keep cursor position:
input.setSelectionRange(cursorPosition, cursorPosition);
};
<input id="input" type="text" placeholder="Digits and - . / only" />
Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993
Anyway, if you still want to try that approach, just keep in mind both e.which and e.keyCode are deprecated, so e.key or e.code should be used instead, which also makes the code easier to understand. Also keep in mind some old browsers used some non-standard codes for some keys, so, for example, left is usually 'LeftArrow' and right is 'RightArrow', but on IE and Legacy Edge they would be 'Left' and 'Right' instead.
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!
Disclaimer: I'm the author.

Related

How to disable typing special characters only not up, down, left and right keys?

I need enable 0 to 9 also up, down, left, right, delete, tab, home, end and etc like (alt, ctrl)
Need Chrome and Firefox browsers
$('.commonNumber').keypress(function(event){
var nbr = event.charCode ? event.charCode : event.keyCode;
// Numbers 8 -> Backspace 9-> Tab
if ((nbr >= 48 && nbr <= 57) || nbr == 8 || nbr == 9 || nbr == 37 || nbr == 38 || nbr == 46 || nbr == 39 || nbr == 40){
return true;
} else {
return false;
}
I enable 37, 38, 39,40,46 this codes are left, up, right, down areo and delete button keys but this keys are also %&('. keys using the same code. so this keys are enabled
});
Your code for normalizing the character code is incorrect. See the bottom of this answer as to why.
If you are using JQuery, it normalizes the which property for you, so you should use event.which to examine the pressed key. The event.which property will be less than 32 for non-printable characters. Therefore, you should always ignore the key when event.which is less than 32. Otherwise, check if it is a character you want to accept.
I also think you should allow the rejected key events to bubble, so use event.preventDefault() to reject a key, rather than return false.
$('.commonNumber').keypress(function(event) {
var charCode = event.which;
if ((charCode >= 32) && ((charCode < 48) || (charCode > 57))) {
event.preventDefault();
}
});
jsfiddle
The code above will limit the accepted printable characters to just numeric digits, while still letting the arrow keys, the delete key, the backspace key, and other control keys to work. Key events will also bubble up, so when the Enter key is pressed, it will still submit the form (if the input element is part of a form).
If you are not using JQuery to handle the keypress event, you have to normalize the event properties yourself. According to this stackoverflow answer, you should do:
var charCode = (typeof event.which == 'number') ? event.which : event.keyCode;
Apparently all browsers, except IE<=8, support the event.which property. In IE<=8, the event.keyCode property holds the Unicode reference number for a printable key instead.
The issue with your original code is that in most browsers (other than IE<=8):
event.charCode is the Unicode reference number of the character for printable keys, and 0 for non-printable keys.
event.keyCode is a system and implementation dependent numerical code. (This is often 0 for printable keys.)
For instance, in Firefox you get:
Ampersand key: event.charCode = 38 and event.keyCode = 0.
Up arrow key: event.charCode = 0 and event.keyCode = 38.
Block or restrict special characters from input fields with jQuery.
You can either return false or call preventDefault() method on event variable.
//this script allows only number input.
$(document).ready(function(){
$("#age").keypress(function(e){
var keyCode = e.which;
/*
8 - (backspace)
32 - (space)
48-57 - (0-9)Numbers
*/
if ( (keyCode != 8 || keyCode ==32 ) && (keyCode < 48 || keyCode > 57)) {
return false;
}
});
});
//this script Not allowing special characters
$("#name").keypress(function(e){
var keyCode = e.which;
/*
48-57 - (0-9)Numbers
65-90 - (A-Z)
97-122 - (a-z)
8 - (backspace)
32 - (space)
*/ // Not allow special
if ( !( (keyCode >= 48 && keyCode <= 57)
||(keyCode >= 65 && keyCode <= 90)
|| (keyCode >= 97 && keyCode <= 122) )
&& keyCode != 8 && keyCode != 32) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type='text' id='name' placeholder='Enter your name'><br/><br/>
<input type='text' id='age' placeholder='Enter your age'>
</div>

Not allowing to add or update any numeric or decimal value once it reach upto two decimal

I need to restrict the user for following things:
1) only allow numeric
2) decimal upto 2 digits
3) allow - backspace, tab,delete buttons
Below code is working fine except one scenario,
Problem is, (Example) when textbox input reach as 6545.12 then after try to change the value as below 65457.12 or 7545.13 then it does not allow and just restrict me. (so, here, not allowing to add new digit or change the existing digit before . or after .)
Can any one please guide me how to solve this issue.
calling below function on keypress event of textbox.
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (
&& // “-” CHECK MINUS, AND ONLY ONE.
(charCode != 8) && (charCode != 9) && (charCode != 37) && (charCode != 39) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)) {
return false;
}
if ($(element).val().indexOf('.') != -1)
{
var index = $(element).val().indexOf('.');
var len = $(element).val().length;
var CharAfterdot = (len + 1) - index;
if (CharAfterdot <= 3) {
return true;
}
else {
return false;
}
}
return true;
}
You might consider including a library that implements input masking (that is, only allowing certain kinds of values to be entered into an input field). Using a library like https://github.com/RobinHerbots/jquery.inputmask you can specify a regular expression as a mask. An example regular expression that only allows numbers up to two decimal places would be [0-9]+(\.[0-9][0-9]?)?. After including the masking library you can either call the mask directly on the element or add a data-inputmask-regex property to your input. See https://github.com/RobinHerbots/jquery.inputmask#usage for more.
Short version: this is a hard problem and other people have already done the work.

Only allowing certain characters

I am in the process of creating a form and I wish to validate the input fields onKeyPress. I have managed to find JavaScript to restrict a field to only allowing numbers to be entered. Now I am trying to adapt that code to only allow letters and a hyphens to be allowed.
The code I have to only allow numbers is as follows...
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
How would I adapt and change this to only allow letters and hyphens instead.
Sorry if this question has been asked before but all I can find is doing it using Jquery etc. and I would like to try and avoid that if I can.
Thanks in advance
var myRegex = /^[A-Za-z\-]+$/;
myRegex.test('hello'); //true
myRegex.test('asdasd-adasd'); //true
myRegex.test('123as'); //false

Javascript keycodes not working in firefox but works well in chrome

I'm just doing my form validation wherein which Phone number has to be only numbers! The code works well in chrome but not in firefox and IE. pls give me some solution
My code is as follows
function noLet(event) {
if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode < 58) {
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
HTML:
onkeypress="noLet(e)"><label id="mobph"></label><font
size="1"><br>Max 10 numbers only allowed!</font>
May i suggest the following code to solve your problem. This is what i am doing. Tested and works like a charm in ie, chrome and firefox:
//return numbers and backspace(charCode == 8) only
function noLet(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >= 48 && charCode <= 57 || charCode == 8)
return true;
return false;
You can use the key/char code to detect whether the key pressed is a number or not a number. First you have to detect what the key/char code is cross browser (remember to use event.keypress as your event to further assure compatibility). Afterwards, you convert it from its decimal value to its character. Then you can parse it as an integer using parseInt() which will return NaN if the first value inside the function cannot be parsed as an int. And then prevent the default action if it is NaN.
var numbersOnly = function(e){
var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
chr = String.fromCharCode(charCode);
if(isNaN(parseInt(chr, 10))) e.preventDefault();
}
<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">
Because on Firefox, at least, it's charCode, not keyCode in the keypress handler, and "returnValue" is ignored (invoke preventDefault() to stop the insertion).
There's compatibility issue of browsers. Here is a solution which I found out in some RND. Hope so it'll help you somehow; Click Here

JS: Recognize dot or delete in keypress

I'd like to execute some code if the user presses the dot (on standard keybord or on numblock). But if I take it over Keycode (110), this is the same like the delete button.
How do I recognize them?
Thanks for your help!
Delete key (usually above arrows) is 46, numpad decimal is 110, and the keyboard period is 190.
This is a pretty good page to know what keycodes are what: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
If this doesn't answer your question, please rephrase it as it's a little confusing what you are looking for.
Use modern JS!
Use event.key === "." || event.key === "Delete", rather than arbitrary number codes!
it's only allow dot and numbers
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46 ) {
return false;
}
return true;

Categories

Resources