87

How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.

Kumar
  • 939
  • 1
  • 7
  • 9
  • 7
    This question has been aswered already: [html5 number input type that takes only integers](https://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers) – lucask May 05 '16 at 06:45
  • 1
    I tried the pattern method, But i would like to have behaviour same as number field. in case of using pattern it doesn't validate until the value is submitted. Just like a number field doesn't allow user to type alphabets, is there any way i could stop period value too. – Kumar May 05 '16 at 08:39

13 Answers13

105

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>
kneeki
  • 1,984
  • 3
  • 13
  • 23
34

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,'');} " >
Stevenfowler16
  • 719
  • 6
  • 20
  • 3
    This is a perfect solution. Anyway, just a tip for Angular developers. onpaste is not allowed on input field, you have to use (paste) which does the same stuff as onpaste. Moreover, do not use event.* into onkeydown because, as Steven as said, is deprecaded. Instead i suggest to use $event on Angular application that should act as the same of event – Mattia_B Nov 05 '20 at 16:59
14

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

Deepu Sasidharan
  • 4,987
  • 8
  • 35
  • 89
  • 26
    Just a note: This seems to only validate on submit of the form that the input is in; it doesn't prevent decimal input, nor does it indicate that the field is in error before the form is submitted. – Bernhard Hofmann Dec 14 '16 at 11:33
  • 7
    Secondary note: 1.0 will return as valid which may or may not correct depending on your what you want. – Michael Feb 24 '17 at 14:58
  • 2
    does not work as I want to check for decimals to be not included when user is typing. – Lonare Mar 07 '18 at 15:12
11

Just plain example using parseInt()

<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />
  • works well. still allows the user to enter a 'fullstop' or 'period' character because `parseInt(0.)` returns `0`. but that makes sense mathematically, because when you enter `0.` without a number after the decimal, the assumption is that it's zero, so `0.` == `0.0`, which equals `0 ` when parsed to an integer. makes sense to me anyway... – camslice Mar 12 '20 at 11:38
  • This works well but not actual since html5. Only if old browsers support is critical – Andrey Doloka Jun 15 '20 at 08:10
  • this does not help as it can save `3` as `3.` – Ylama Jun 23 '20 at 13:28
10

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

Nigel Fds
  • 763
  • 1
  • 11
  • 27
3
<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/

Npsad
  • 388
  • 3
  • 11
1

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 });

0

You should post what you have tried when asking questions.

To use integers only, change the following attribute.

step="any"

to

step="1"
Kake_Fisk
  • 977
  • 10
  • 20
  • 22
    using step attribute still allows user to type decimal value. Just like number field doesn't allow user to type alphabets, is there any way that i could restrict user to type float values – Kumar May 05 '16 at 08:41
0

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 '.'.

Terrorbladezz
  • 61
  • 1
  • 5
0

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" />
0
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57"  name="quantity">
Hussain
  • 34
  • 4
0
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
        return false;
    return true;     
}
Dave
  • 3,046
  • 7
  • 19
  • 32
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/31249995) – MD. RAKIB HASAN Mar 16 '22 at 09:21
-2

@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.

Prachi
  • 11
  • 1