Related
I can't find the right regex pattern for this, even though there are a lot of questions in this kind.
I dont want the user to be able to type or input
<td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" /></td>
-1.0 (Negative values)
String Values and any character
1.0 (Decimal Values)
No range Limit
I only want to accept positive whole numbers
SOLVED
no need for regex, I did not know this :D
<td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" onkeypress="return event.charCode >= 48 && event.charCode <= 57"</td>
To disallow any input but numeric, you may use
<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
^------------....
<form id="mfrm">
<table>
<tr>
<td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td>
<td><input type="Submit"/></td>
</tr>
</table>
Here, the event.charCode == 8 || event.charCode == 0 || event.charCode == 13 condition handles the case when DELETE, BACKSPACE or ENTER keys are pressed (important for Firefox, see Mohit's comment below and datashaman's comment related to enabling the ENTER key).
The event.charCode >= 48 && event.charCode <= 57 means that only 0 (decimal code 48) and all other digits up to 9 (decimal code 57) will be returned.
You can use type, min and oninput
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
<form>
<label>Input with positive numbers only</label><br/><br/>
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
</form>
I tried a lot of different solutions to achieve this, and I finally came up with this one, which does the job perfectly for us. It works for typing and for copy/paste, and I couldn't find any unwanted side-effects.
<form>
<input
type="number"
min="0"
step="1"
onfocus="this.previousValue = this.value"
onkeydown="this.previousValue = this.value"
oninput="validity.valid || (value = this.previousValue)"
/>
</form>
It is like Nikhil Mahirrao's solution, but it will cause invalid keystrokes to be simply ignored without emptying the input.
To allow only number values you can use as follows:
<td><input type="number" pattern="\d+" name="itemConsumption" /></td>
If it comes to HTML5 then you might try min attribute:
<input type="number" min="0">
You can use this regex pattern for whole numbers [0-9]* or \d*
[0-9] is range you can type 0 to 9 and * means not expecting any number or may you type infinite numbers
Maybe this jQuery Codepen snipet will be helpful for someone.
It's for type="number" (not "text"):
<input class="js-input-absint" type="number" step="1" min="18" max="150" name="age" value="50">
with [0-9] allowed inputs only. In the input will printed/pasted only numbers [0-9] with an min-max range (optional).
Some explanations: The code displays only numbers at the input stage, and does not reset the value to "" (empty) in case of inputting not valid number values like it does by default for type="number". And you can't use the attribute pattern="/^[0-9]*$/" for an input type="number".
var $inputAbsint = $('.js-input-absint');
if ($inputAbsint.length) {
$(document).on('keypress', '.js-input-absint', function (event) {
var allowed = /^[0-9]|Arrow(Left|Right)|Backspace|Home|End|Delete$/;
return allowed.test(event.key);
}).on('focusout paste', '.js-input-absint', function () {
var $input = $(this);
var defaultValue = this.defaultValue || $input.attr('min');
// Important(!): Timeout for the updated value
setTimeout(function () {
var current = $input.val();
var regexNumbers = new RegExp(/^[0-9]*$/, 'g');
var isNumbersOnly = regexNumbers.test(current);
// Clear wrong value (not numbers)
if ((current === '' || !isNumbersOnly) && defaultValue.length) {
$input.val(defaultValue);
current = defaultValue;
}
// Min/Max
var min = parseInt($input.attr('min'), 10);
var max = parseInt($input.attr('max'), 10);
var currentInt = parseInt(current, 10);
if (!isNaN(min) && !isNaN(currentInt) && currentInt < min) {
$input.val(min);
}
if (!isNaN(max) && !isNaN(currentInt) && currentInt > max) {
$input.val(max);
}
}, 100);
});
}
You can't press ' - ' button on keyboard.
<!--HTML Code is below-->
<input type="text" name="value1" id="value1" class="form-control" required="required" onkeyup="keyCode(event)">
<!--JQuery Code is below-->
<script>
$(document).ready(function() {
$value1.on("keyup", function keyCode(event){
var x = event.keyCode;
if (x == 109 || x == 189) {
event.preventDefault();
alert ("You can't enter minus value !");
}
});
});
</script>
Keycode of '109' represent numeric side minus button of keyboard. Keycode of '189' represent minus button above of the character buttons.
Nikhil Mahirrao answer is elegant and short!
I wanted something similar, however the field should not bounce back to an empty string, but in addition simply ignore any input that is not a number. Also, leading zeros should be filtered.
... oninput="filterNonNumbers(this)" ...
function filterNonNumbers(inputElement) {
let valOriginal = inputElement.value;
let valFiltered = valOriginal.split('').filter(c => c.charCodeAt(0) >= 48 && c.charCodeAt(0) <= 57 ? c : '').join('').replace(/^0+/, '');
if (valOriginal !== valFiltered) {
inputElement.value = valFiltered;
}
}
Of course, it works just like Nikhil's code when typing directly as well as when pasting via the clipboard.
Perhaps someone has a similar, extended requirement.
Just wanted to throw out a solution to round it off upon input.
<input id="numinput" type="number" step=1
oninput="validateWholeNmericInput('numinput', this.value)">
function validateWholeNumericInput(id, val){
if(!Number.isInteger(val)){
var newval = Math.round(val);
document.getElementById(id).value = newval;
}
}
I have an input field which is of number type, when I enter the dot I am not getting the value. So what I am trying to achieve is the I don't want the user to enter dot on the input field
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)"/>
on each number entering I am getting the value, but when I type dot (.), I am not getting how can I block this when user type it
<input name="num" type="number" min="1" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
referance from this url
https://stackoverflow.com/a/44379790/4316212
Add This oninput="this.value = this.value.replace(/[^0-9]/, '')"
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)" oninput="this.value = this.value.replace(/[^0-9]/, '')"/>
if you want to block '.' you can use this way,
function handleChange (value) {
console.log(value)
}
var inputBox = document.getElementById("inputBox");
var invalidChars = [
".",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" onchange="handleChange(this.value)/>
It is generally not a good idea to use inline event handlers.
For more control you should check/use the atributes of a number input.
If you want to completely control the input, use a readonly field and handle it using your own handler. Here's a snippet using event delegation. It uses the step attribute from the number input field for adding/subtracting.
document.addEventListener('click', handle);
function handle(evt) {
if (evt.target.dataset.numinput) {
const inp = document.querySelector(`#num`)
inp.value = ( +inp.value + +(`${evt.target.dataset.numinput}${inp.step}`) )
.toFixed(2);
}
}
<input id="num" type="number" step="0.1" readonly/>
<button data-numinput="-"> - </button>
<button data-numinput="+"> + </button>
I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />
Im trying to limit to X number the characters in a input (type of number). ive tried a lot of options and none seems to work. I dont want to use the option tel as it needs the numeric keyboard on a mobile device (yes, with ., and all the symbols) I tried also the pattern solution but it only worked for iOS, didnt work in android (displayed the normal keyboard).
The best way would be that if the user hits the limit dont let him type anymore, if he wants to highlight the text and re-type a different number he is allow to. Just not let him type more than the specified number of characters.
So, any help is appreciated.
Note: charCode is non-standard and deprecated, whereas keyCode is simply deprecated.
Check this code
JavaScript
<script>
function check(e,value)
{
//Check Charater
var unicode=e.charCode? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)if( unicode == 46 )return false;
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength()
{
var fieldLength = document.getElementById('txtF').value.length;
//Suppose u want 4 number of character
if(fieldLength <= 4){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
and HTML input with number type below
onInput //Is fired also if value change from the side arrows of field in Chrome browser
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
Fiddle Demo
Update -- Little bit generic code example
Change above function into this one
function checkLength(len,ele){
var fieldLength = ele.value.length;
if(fieldLength <= len){
return true;
}
else
{
var str = ele.value;
str = str.substring(0, str.length - 1);
ele.value = str;
}
}
In HTML use like this
<!-- length 4 -->
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />
Demo
Another option - the tel input type abides by the maxlength and size attributes.
<input type="tel" size="2" maxlength="2" />
<input type="tel" size="10" maxlength="2" />
May be it will be useful.
Here is field to input Patient Age. It allows to input 3 numbers only.
HTML
<input autocomplete="off" class="form-control" id="Patient_Age" max="150" maxlength="3" name="PatientAge" placeholder="Age" size="3" type="number" value="0">
JS
<script>
$(function () {
$("#Patient_Age").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter
if ($(this).val().length <= 2 || $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
// (e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
event.preventDefault();
}
// Ensure that it is a number and stop the keypress
if ($(this).val().length <= 2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
else {
event.preventDefault();
}
});
}); // end of $
</script>
The HTML5 number type input has min and max attributes.
If you wanted to limit the number of characters to 1 you could set a min of 0 and a max of 9.
You can also set the step attribute, which is 1 by default, but would come in use if you wanted the ability to select decimals or other rounded numbers.
<input type="number" maxlength="1" max="9" min="1" size="1" />
Here's the full demo
please review this code
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);"
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>
I think this requires the onkeyup event handler.
Use this handler to keep on entering numbers till 5 keyup's are encountered. After this , don't let the the number to be entered by returning a 0, unless key pressed is backspace or delete .
You can try thiss jQuery code :
In HTML
<input type="number" id="number" />
In JS
$(document).ready(function () {
var element = document.getElementById('number');
$("#number").keydown(function (event) {
// Allow only backspace and delete
if($(this).val().length <= 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 )
{
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// let it happen, don't do anything
} else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
}else{
event.preventDefault();
}
});
});
I have not any idea wheather its working on IOS N Android but its work on all browser.
DEMO
For Decimal values, lets say "25.2" code is as under.
if(thisObj.value.indexOf(".") >=0)
{
if(fieldLength <= 4)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
else
{
if(fieldLength <= 2)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
You can easily do it like this,
<input type="text" pattern="\d*" maxlength="4">
Proper way 2020 for type number is to check on keydown validation and it should work like this: onkeypress="checkValidation(fieldValue);" <-- on input in html and in js:
checkValidation(a) {
if (`${a}`.length < 8) {
return true;
} else {
return false;
}
}
Use the maxlength property like this.
<input type="text" maxlength="5"/>
Dude why go for javascript? Just try
<input type="text" maxlength="4" size="4">
maxlength will anyways define a maximum length for the input field.
Hope this solved the problem :)
EDIT: Since you specifically want numbers, why dont you use the above and then run a jquery validation to check for numbers? That will also work..
EDIT: Okay, try
<input type="number" name="pin" min="1000" max="9999">
Did you try the property maxlength ?
<input type="text" maxlength="5" name="user" >
I need to have a textbox, where, whenever typed inside should ONLY allow numbers [0-9]. I've used type="number" which definitely holds the client side validation but also allows to type other alphabets. I can do it by tracking each keydown and matching with regex but I was wondering if there is any way I can restrict to type using only html tags and NOT defining any functions in JavaScript to compare in each keydown?
Code not sufficient to do so is:
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number">
Any help is appreciated.
You can use jquery.numeric plugin.
See
here similar question.
$(document).ready(function(){
$(".numeric").numeric();
});
Try this
define javascript function
function for allowed number with decimal as below
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
function for allowed only number not decimal is as below
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode < 48 || charCode > 57))
return false;
return true;
}
Html
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number" onkeypress="return isNumberKey(event)">
input type="number" for getting Numeric Keyboard on Mobile Device
Java-Script
function numbersonly(myfield, e)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// only one decimal point
else if ((keychar == "."))
{
if (myfield.value.indexOf(keychar) > -1)
return false;
}
else
return false;
}
Html
<input type="number" onkeypress="return numbersonly(this, event)"/>
Browsers behave differently. In Chrome the following code:
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number">
<input type="submit">
will work for you only if it is in a form and only after the user clicks the submit button.
If you don't mind using a bit of Javascript, this might help JS-BIN Demo:
<input type="number" onkeyup="if(!this.checkValidity()){this.value='';alert('Please enter a number')};"/>
You will have to have your input box inside a form and with a submit button. The form validation happens at the submission of the form. See a demo here: http://jsfiddle.net/ds345/Q4muA/1/
<form>Number:
<input type="number" name="Number" value="10">
<br>
<input type="submit" value="Submit" />
</form>
Try this:-
$("#txtAge").keydown(function (e) {
if(e.key=='e' || e.key=='.' || e.key=='-')
return false;
});
I notice that the question was posted around 2013. Anyways, now type="number" is restricting alphabets and special characters other that 'e','.' and '+' as 'e' and '.' are considered for exponential numbers like 1.2e+12, '.' is considered for decimal numbers.
just add - min="0" max="9" onkeydown="return false;"
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number" min="0" max="9" onkeydown="return false;">