When I'm giving input type number the letter e
and special charecters are also displaying in input field. I want to display only digits. How to block them?
<input type="number">
When I'm giving input type number the letter e
and special charecters are also displaying in input field. I want to display only digits. How to block them?
<input type="number">
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
// 0 for null values
// 8 for backspace
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
You can block entering those chars with keydown
event
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e
, suggested solution will fail.
What happens when you enter 1e
is that, input field checks if it's a number, and if it's not (1e
is not) it throws a warning:
The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
and the value
property is set to ""
.
If you check the field's properties, you'll find valueAsNumber
property. If the entered value is a number, input field parses the value and stores it in valueAsNumber
. Since 1e
is not a number, it evaluates to NaN
, and NaN
is assigned to valueAsNumber
and value
is set to ""
. Though you still see 1e
on the input field.
I've asked a question related to this problem, but no solution yet.
Instead on trying to block values, you can try to replace values that are non numeric.
If you choose to handle keycodes, you will have to handle numKeys
, numPad
, shift +
, crtl +
etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.
Also that way whatever you enter into the array will be prevented from being keyed in into the input box
Note - take the 'elementid' as the id of the element you want to apply this to similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")
var invalidChars = ["-", "e", "+", "E"];
$("input[type='number']").on("keydown", function(e){
if(invalidChars.includes(e.key)){
e.preventDefault();
}
}):
This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.
UPDATE
Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.
Here's a pretty concise solution using jQuery based on some of the other solutions:
$("input[type=number]").on("keydown", function(e) {
var invalidChars = ["-", "+", "e"]; //include "." if you only want integers
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
You can check it if it's a number or not.
// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
if (isNaN(e.key)) {
return false;
}
});
You can do it easily using jQuery
Try this code
$(function() {
$("#input").keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
$(".alert").html("Enter only digits!").show().fadeOut(2000);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
With onKeyUp, onKeyPress or onKeyDown events the same can be restricted.
onKeyDown = {
(e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:
JQuery
You can also use the following code if you want to accept decimals(.)
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key)!=-1){}
else if (e.key=='.' && this.value!='' && (this.value.match("\.") || []).length==0){}
else{e.preventDefault();}
});
Here is React solution, hope it will help somebody
const numberInputInvalidChars = ['-', '+', 'e'];
<input
type="number"
onKeyDown={(e) => {
if (numberInputInvalidChars.includes(e.key)) {
e.preventDefault();
}
}}
></input>
Yo can Block by using some JQuery codes
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key) == -1) {
e.preventDefault();
}
});
This will affect on all Numeric typed Input
I'm not sure the details of your use case, but you may not need to do a lot to handle these yourself. For starters, you can set a min, which can be used to prevent negatives, as well as a max value and a step value if that's useful. It turns out the default step is 1, so it requires integers unless you specify a decimal step value.
When it comes to dealing with the "e" in numbers, you can use Number() to convert text to a number, and it'll automatically convert the "e", as well as any "+" sign:
> Number("5e3")
5000
> Number("+42")
42
If you really need the submitted value to be normalized, you can convert it back in place. I think probably the most user friendly time to do it would be on blur:
input.addEventListener('blur', () => {
if (input.value !== '' && input.checkValidity()) {
input.value = Number(input.value);
}
});
in the input of numeric type the events for characters with value different from [0-9] is an object with
event.target.value: ""
so just prevent events that have no value
if (!event.target.value) {
event.preventDefault();
};
Here is a plain html/js solution which:
+
, -
, .
, E
, e
(type="number"
)+
, -
, .
, E
, e
from being registered in the input field (onkeydown="if (/^[eE.\+\-]$/.test(event.key)) event.preventDefault();"
)onPaste="if (!/^\d+$/.test(event.clipboardData.getData('text/plain'))) event.preventDefault();"
)<input
type="number"
onkeydown="
if (/^[eE.\+\-]$/.test(event.key))
event.preventDefault();
"
onPaste="
if (!/^\d+$/.test(event.clipboardData.getData('text/plain')))
event.preventDefault();
"
>
If you would also like to trim leading zeroes, you can add this:
oninput="
return
event.target.value.replace(/^0*/, '') ||
'0';
"
If you want + sign in your phone number field then you can use this code.
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />