如何避免输入类型号中的 Decimal 值

如何避免在 HTML5中输入十进制值。目前它允许用户输入十进制值。

156175 次浏览

You should post what you have tried when asking questions.

To use integers only, change the following attribute.

step="any"

to

step="1"

Use pattern attribute

<input type="number" name="num" pattern="[0-9]" title="Numbers only">

For more details http://www.w3schools.com/tags/att_input_pattern.asp

FIDDLE

An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle

<form action="#" method="post">
Numbers: <input name="num"
type="number"
min="1"
step="1"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
<input type="submit">
</form>

Based on other answers here, I tried this:

<input id="storeId" min="0" pattern="[0-9]" onkeypress="return !(event.charCode == 46)" step="1" title="Must be an integer number" type="number" >

I just blocked input of dot, but again this does not block paste.

ASCII DOT . character is 46

Just plain example using parseInt()

<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />

I ended up checking to see if a user types in a period then preventing the event from propagating.

Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}"  oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">

Caution Experimental. Only partially works on chrome: Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >

A simple regex can help sort with this issue .

var re = new regExp('[.]+) ;
if(!re.test(num)){listOfNumbers.push(num)};

not letting the user type in a '.' on the input might not be a viable option when you are dealing with multiple cultures and interpretations of '.'.

You guys can try this This function does not allow user to paste unwanted characters and also disallow user to enter .+-E

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" >

`

If error occured in your JS. You can add this `$(document).ready(function() { code });

<input type="number" onkeydown="return event.keyCode !== 190">

This will Restrict period(.) input.For any Key restriction: https://css-tricks.com/snippets/javascript/javascript-keycodes/

@Html.TextBoxFor(model => model.num, new { @class = "form-control input-sm",@maxlength = 5 ,@oninput = "this.value = this.value.replace(/[^0-9]/g, '');"})

In MVC, above solution works.

Try this :

<input type="number"  value=""  min="0" oninput="this.value=(parseInt(this.value)||0)" onkeypress="return !(event.charCode == 45||event.charCode == 46||event.charCode == 43)"  class="form-control" step="any" />
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57"  name="quantity">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
return false;
return true;
}