I am validating a textbox that will allow only numeric values of fixed length. I have done workaround to allow certaing keys like backspace, delete, arrow keys etc and this is working fine.
I am not able to paste any text in the textbox as well as copy text from the textbox in Firefox. In chrome its working fine.
Here is the code I have written.
function validateTransactionId(event)
{
var transactionId = document.getElementById('transactionId').value;
var charCode = (event.which) ? event.which : event.keyCode;
// Allow: backspace, delete, tab, escape, enter
if ($.inArray(charCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: home, end, left, right
(charCode >= 35 && charCode <= 39)) {
return true;
}
if ((charCode < 48 || charCode > 57))
return false;
if (transactionId.length == 11)
return false;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Transaction ID" id="transactionId"
onkeypress="return validateTransactionId(event)" />
I want to enable copy paste in this textbox. Any help here will be much appreciated.
A few things to consider.
First, you may want to include the v character to account for Ctrl+V or Cmd+V for pasting.
if ($.inArray(charCode, [46, 8, 9, 27, 13, 110, 118]) !== -1
Secondly, if someone is pasting, the length may already be more than 11. So you need to change your if statement.
if (transactionId.length > 11) return false;
Third, if someone pastes a non-numeric string less than 11 characters, it will still accept it.
My suggestion would be instead of trying to validate individual key presses that you validate the value of the textbox. You can use a regular expression match to strip out non-numeric characters.
transactionId = transactionId.replace(/\D/g, "");
I have a javascript program that, in part, poses a division problem and asks for the quotient and remainder to be inserted in two different textboxes. The program in this instance looks like this:
!(C:\Users\Owen Walker\Dropbox (Personal)\Sebzo javascript\quotient_remainder.JPG)
For some reason--the program is fairly complicated--when both textboxes are visible, the user cannot Tab and Shift+Tab from one textbox to the other.
I have therefore written two functions: handleTabInQuotientTextbox() and handleShiftTabInRemainderTextbox(), that, when called in onkeyup from the quotient and remainder textboxes, set the focus on the other textbox. In other words, they do the right thing when Tab is pressed in the quotient textbox, i.e., the caret goes to the reminder textbox, and vice versa when the Shift+Tab keys are pressed in the remainder textbox. What's wrong is that one can no longer enter numbers or other text into the two textboxes.
Here is the code for the two functions:
function handleTabInQuotientTextbox(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode == 9 && tentative_game_chosen == 'rd') {
document.getElementById("user_input_for_remainder_div").focus();
}
return false;
}
function handleShiftTabInRemainderTextbox(evt) {
var e = event || evt; // for trans-browser compatibility
if(e.shiftKey && event.keyCode == 9 && tentative_game_chosen == 'rd') {
document.getElementById("user_input_div").focus();
}
return false;
}
What am I doing wrong?
Any thoughts would be much appreciated.
If I use onkeypress, I can return all characters in a perfectly readable way. Uppercase letters work, !, ? , ', etc all works great. The problem is that I cant detect a backspace.
onkeydown on the other hand does detect the backspace key. The problem here is that it does not recognize shift being pressed simultaneously with a letter key, it's always uppercase, I can't get apostrophes, exclamation marks, question marks are upside down, etc.
How can I return natural language characters while at the same time having the ability to use backspace and delete unwanted characters?
<form action="">
<textarea id="myArea" type="text" onkeydown="return myKeyPress(event)" ></textarea>
</form>
<script>
var socket = io();
function myKeyPress(e){
var keynum;
var letter;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
letter = String.fromCharCode(keynum);
socket.emit('theText', letter);
}
socket.on('theText', function(msg) {
document.getElementById('myArea').value += msg;
})
</script>
It's not necessarily an either-or problem - use onkeydown, see if they pressed backspace, otherwise do nothing. Use onkeypress to detect other letters.
How to disable text when using placeholder?
jsfiddle
<input type="number" placeholder="Min.">
EDIT
The input number should allow the user to enter only numbers.
This stops the user from inputting any character which is not a number, while still allowing them to use non-printable keys (ctrl, alt, backspace, enter, etc.)
This first part is from this answer to a different question
The second part basically checks every time the user presses a key, to see if that key was...
Printable, and
Not a number
If both of these conditions are met, prevent the character from being entered.
// https://stackoverflow.com/a/12467610/4639281
function printable(keycode) {
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
return !!valid;
}
// This part is me
document.getElementById('min').onkeydown = function(e) {
var char = String.fromCharCode(e.keyCode);
if(printable(e.keyCode) & isNaN(char)) {
e.preventDefault();
}
}
<input type="text" placeholder="Min." id="min">
The jquery numeric plugin did the trick. Thank you all for the help. I had to write more text because the answer should be 30 characters minimum.
$(document).ready(function(){
$(".numeric").numeric();
});
My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.