197

I need to make sure that a certain <input> field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.

Is there a neat way to achieve this?

chtenb
  • 14,924
  • 14
  • 78
  • 116
  • http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input – alexblum Dec 19 '12 at 12:42
  • 2
    Take a look at this [link][1], which has enough info. [1]: http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input – Maheshkumar Dec 19 '12 at 12:46
  • This one may also come in handy: http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – chtenb Sep 12 '13 at 14:27

34 Answers34

345

HTML 5

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purposes, you can have JS validation as below:

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)" />

If you want to allow decimals replace the if-conditio" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Viral Patel
  • 8,506
  • 3
  • 32
  • 29
  • 8
    Yep, this works for me in both firefox and chrome. Weird that js is necessary for such a simple thing. – chtenb Dec 19 '12 at 13:08
  • @Chiel92 - **Just to inform** it is not necessary. you can do so by server side scripting languages `php` & others. If browser has javascript disabled this won't work ! and you may enter any value from `firebug` or any other developer tools. – Pankit Kapadia Dec 19 '12 at 14:42
  • I'm very aware of that. Though it's for a tablet app, I will do serverside validation anyway. But the value of the input influences other UI elements, so it needs to be done clientside as well. – chtenb Dec 19 '12 at 14:50
  • 7
    Doesn't work in chrome 30. I have no trouble at all typing letters into your "number" input in the fiddle. Hmmm... – Ben Jun 30 '13 at 19:23
  • 2
    What if someone want to enter float values like 8.9 ? – syed shah Nov 16 '13 at 14:56
  • 6
    for a more robust solution, also consider copy and paste can add letters to this example! – Neil Feb 17 '14 at 11:43
  • 3
    Oops!! first line must changed to : `var charCode = (evt.which) ? evt.which : evt.keyCode;` – peiman F. Jul 17 '14 at 22:34
  • +1 and thanks to @Viral, I seen it and i tried to enhance this way with my knowledge and search results, so I wrote another with min and max range. You could see in: http://stackoverflow.com/questions/2013229/jquery-numeric-textbox-with-min-and-max-ranges/25710687#25710687 Please tell me if you have any additional idea. – QMaster Sep 07 '14 at 13:36
  • Hi, any one tell me how to set condition that enter value should be number and also greater than or equal to 20. Thanks in advanced. – Muddasir Abbas Oct 16 '14 at 07:13
  • Why would the shift key return true? I know its not necessarily a problem but i'm just curious. – LewisJWright Feb 01 '17 at 11:55
  • It accepts numbers such as 12.12.23. (with more than 1 decimals) – Joyston Oct 04 '17 at 05:36
  • This code works great. Just 1 slight problem. It allows me to type in special characters such as: ãôéè, etc. etc. Any idea how to block those as well? – Brad Ahrens Nov 22 '17 at 07:41
  • if you use ctrl + v, it will break. – grant sun Aug 01 '18 at 15:06
  • check out my answer – Normajean Apr 08 '20 at 02:50
  • Upvoted for the first paragraph and downvoted for the rest. – Armen Michaeli May 13 '21 at 16:15
51

You can also use the pattern attribute in html5:

<input type="text" name="name" pattern="[0-9]" title="Title" /> 

Input validation tutorial

Although, if your doctype isn't html then I think you'll need to use some javascript/jquery.

Gonzalo Garcia
  • 6,192
  • 2
  • 29
  • 32
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
31

Quick and Easy Code

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />

This will permit usage of numbers and backspace only.

If you need decimal part too, use this code fragment

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
abhijithvijayan
  • 835
  • 12
  • 17
  • Is there a way to limit the number of decimals, as to use it for prices? – Allan Nov 18 '20 at 23:00
  • it returns a boolean value so I guess you can add another check that takes the current value and checks if the length is under what you specified. – abhijithvijayan Nov 19 '20 at 15:05
18

Please try this code along with the input field itself

<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>

it will work fine.

subindas pm
  • 2,668
  • 25
  • 18
18

You can use following one line code as :

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >

It will accept numbers ony.

w.Daya
  • 443
  • 1
  • 7
  • 12
10

You can use an <input type="number" />. This will only allow numbers to be entered into othe input box.

Example: http://jsfiddle.net/SPqY3/

Please note that the input type="number" tag is only supported in newer browsers.

For firefox, you can validate the input by using javascript:

http://jsfiddle.net/VmtF5/

Update 2018-03-12: Browser support is much better now it's supported by the following:

  • Chrome 6+
  • Firefox 29+
  • Opera 10.1+
  • Safari 5+
  • Edge
  • (Internet Explorer 10+)
starbeamrainbowlabs
  • 5,692
  • 8
  • 42
  • 73
  • 1
    It appears to work very nicely in chrome, but not in firefox. – chtenb Dec 19 '12 at 13:01
  • Ah. That is because firefox does not support input type=number. Alternatively, you could use some javascript to validate the input as the user inputs the text. Answer updated. – starbeamrainbowlabs Dec 19 '12 at 13:11
  • The jscript on http://jsfiddle.net/VmtF5/, will also not work. Even if 1 digit is at the start of character, the validation fails. Try it yourself on jsfiddle – Akshay Apr 07 '14 at 09:24
  • @aarn It works for me (see http://i.imgur.com/AWdmEov.png ), what browser are you using? – starbeamrainbowlabs Apr 07 '14 at 17:45
  • @starbeamrainbowlabs I am using firefox. Also, enter 6abc, it will not show you the error – Akshay Apr 09 '14 at 17:29
  • @aarn I see what you mean now. That happens beause the javascript used to detect whether the number is valid or not uses `parseFloat()`, which allows extra chracters after the number, for example `123kg`. If you wanted to *only* have the numbers, you might want something like this: http://jsfiddle.net/b72Qr/ (from http://stackoverflow.com/questions/1779013/check-if-string-contains-only-digits) – starbeamrainbowlabs Apr 10 '14 at 09:11
9

You can use the <input> tag with attribute type='number'

For example you can use <input type='number' />

This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
8

I have used a regular expression to replace the input value with the pattern needed.

function restrictNumber(e) {
  var newValue = this.value.replace(new RegExp(/[^\d]/, 'ig'), "");
  this.value = newValue;
}

var userName = document.querySelector('#numberField');
userName.addEventListener('input', restrictNumber);
<input type="text" id="numberField">
Michael M.
  • 10,486
  • 9
  • 18
  • 34
7
<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />

and in JS:

function isNumber(e){
    e = e || window.event;
    var charCode = e.which ? e.which : e.keyCode;
    return /\d/.test(String.fromCharCode(charCode));
}

or you can write it in a complicated but useful way:

<input onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" type="text" name="myinput" id="myinput" />

Note: cross-browser and regex in literal.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Fredrick Gauss
  • 5,126
  • 1
  • 28
  • 44
  • how would you add ability to put input like .5 or .3? – user3591637 Oct 23 '14 at 23:31
  • Then you have to consider first and second characters (`0.43` or `.43`) that could be done with checking the value of current input plus pressed key. This would be ugly in one-line code, I recommend to use a function for this. To test integer or float, check [here](http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer). – Fredrick Gauss Oct 27 '14 at 08:27
  • 1
    you can't delete a number entered by mistake – Chris Sim Jan 13 '17 at 11:05
6

function AllowOnlyNumbers(e) {
  e = (e) ? e : window.event;

  var clipboardData = e.clipboardData ? e.clipboardData : window.clipboardData;
  var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
  var str = (e.type && e.type == "paste") ? clipboardData.getData('Text') : String.fromCharCode(key);

  return (/^\d+$/.test(str));
}
<h1>Integer Textbox</h1>
<input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" />
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Sameh Saeed
  • 71
  • 1
  • 8
4
<input 
    onkeyup="value=isNaN(parseFloat(value))?1000:value" 
    type="number" 
    value="1000"
>

onkeyup triggers when the key is released.

isNaN(parseFloat(value))? checks if the input value is not a number.

If it is not a number the value is set to 1000 : If it is a number the value is set to the value.

Note: For some reason it only works with type="number"

To make it even more exciting, you can also have a boundary:

<input 
    onkeyup="value=isNaN(parseFloat(value))||value<0||value>9000?1000:value"
    type="number"
    value="1000"
>
Michael M.
  • 10,486
  • 9
  • 18
  • 34
user40521
  • 1,997
  • 20
  • 8
4

I fought with this one for a bit. Many solutions here and elsewhere seemed complicated. This solution uses jQuery/javascript alongside HTML.

$(document).on('change', '.validateNumber', function() {
  var abc = parseInt($(this).val());
  if (isNaN(abc)) abc = 1;
  $(this).val(abc);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" min="1" class="validateNumber">

In my case I was tracking small quantities with a minimum value of 1, hence the min="1" in the input tag and abc = 1 in the isNaN() check. For positive-only numbers you could change those values to 0 and even simply remove the min="1" from the input tag to allow for negative numbers.

Also this works for multiple boxes (and could save you some load time over doing them individually by id), just add the "validateNumber" class where needed.

Explanation

parseInt() basically does what you need, except that it returns NaN rather than some integer value. With a simple if(), you can set the "fallback" value that you prefer in all the cases NaN is returned.

Also, W3 Schools states here that the global version of NaN will type cast before checking which gives some extra proofing (Number.isNaN() does not do that). Any values sent to a server/backend should still be validated there!

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Isaiah
  • 484
  • 5
  • 16
4
<input type="phone" onkeyup="value=value.replace(/[^\d]/g,'')" name="personalPhone" lay-verify="personalPhone" autocomplete="off" placeholder="Input Your Telephone Number" class="layui-input">

Add inside your input tag: onkeyup="value=value.replace(/[^\d]/g,'')"

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 3
    Welcome to SO! Unfortunately, this is a 5 1/2 year old question that already has an accepted answer. You might want to browse questions without answers here: https://stackoverflow.com/unanswered – JoshG Jul 05 '18 at 04:35
4

Simple enough?

inputField.addEventListener('input', function () {
  if ((inputField.value/inputField.value) !== 1) {
    console.log("Please enter a number");
  }
});
<input id="inputField" type="text">
Normajean
  • 1,075
  • 3
  • 11
  • 28
3

How about using <input type="number"...>?

http://www.w3schools.com/tags/tag_input.asp

Also, here is a question that has some examples of using Javascript for validation.

Update: linked to better question (thanks alexblum).

Community
  • 1
  • 1
dan1111
  • 6,576
  • 2
  • 18
  • 29
3

If you can use HTML5 you can do <input type="number" />

If not you will have to either do it through javascript as you said it doesn't get submitted to do it from code behind.

function validate() {
  var returnString;
  var text = document.getElementById('numbersOnly').value;
  var regex = /[0-9]|\./;
  var anArray = text.split('');
  for (var i = 0; i < anArray.length; i++) {
    if (!regex.test(anArray[i])) {
      anArray[i] = '';
    }
  }
  for (var i = 0; i < anArray.length; i++) {
    returnString += anArray[i];
  }
  document.getElementById('numbersOnly').value = returnString;
}
<input id="numbersOnly" onkeypress='validate()' />

P.S: I didn't test the code but it should be more or less correct if not check for typos. You might wanna add a few more things like what to do if the string is null or empty etc. Also, you could make this quicker.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
czioutas
  • 1,032
  • 2
  • 11
  • 37
3

I use this for zip codes, quick and easy.

<input type="text" id="zip_code" name="zip_code" onkeypress="return event.charCode > 47 && event.charCode < 58;" pattern="[0-9]{5}" required></input>
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Justin Buser
  • 2,813
  • 25
  • 32
3

The accepted answer:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

It's good but not perfect. It works out for me, but I get a warning that the if-statement can be simplified.

Then it looks like this, which is way prettier:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Chris H.
  • 117
  • 1
  • 3
3

I updated some answers posted to add the following:

  • Add the method as extension method
  • Allow only one point to be entered
  • Specify how many numbers after the decimal point is allowed.
String.prototype.isDecimal = function isDecimal(evt,decimalPts) {
    debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
        return false;
  
    //Prevent more than one point
    if (charCode == 46 && this.includes("."))
        return false;

    // Restrict the needed decimal digits
    if (this.includes("."))
    {
        var number = [];
        number = this.split(".");
        if (number[1].length == decimalPts)
             return false;
     }

     return true;
};
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Plexis Plexis
  • 302
  • 2
  • 12
2

If not integer set 0

$('#min-value').change(function() {
  var checkvalue = $('#min-value').val();
  if (checkvalue != parseInt(checkvalue))
    $('#min-value').val(0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="min-value" />
Michael M.
  • 10,486
  • 9
  • 18
  • 34
websky
  • 3,047
  • 1
  • 33
  • 31
2

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input Key Filter Test</title>
 <meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 
 <!-- For compatibility of IE browser with audio element in the beep() function.
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>
 
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
 
</head>
<body>
 <h1>Integer field</h1>
<input id="Integer">
<script>
 CreateIntFilter("Integer", function(event){//onChange event
   inputKeyFilter.RemoveMyTooltip();
   var elementNewInteger = document.getElementById("NewInteger");
   var integer = parseInt(this.value);
   if(inputKeyFilter.isNaN(integer, this)){
    elementNewInteger.innerHTML = "";
    return;
   }
   //elementNewInteger.innerText = integer;//Uncompatible with FireFox
   elementNewInteger.innerHTML = integer;
  }
  
  //onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
  , function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); }
 );
</script>
 New integer: <span id="NewInteger"></span>
</body>
</html>

Also see my page "Integer field:" of the example of the input key filter

Andrej
  • 679
  • 5
  • 14
2

I found that this works. It improves the user experience by showing a numeric keyboard and throws an error when the entered value isn't a number.

const numInput = document.querySelector("input[type='text']");

numInput.addEventListener("input", () => {
  if (!/^\d+$/.test(numInput.value)) {
    alert("Input must be a number!");
  }
});
<input type="text" inputmode="numeric" pattern="[0-9]+">

The JS will display an alert if the input isn't a number.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
mikenjuki
  • 21
  • 5
2

you can use this too

<input onkeypress="return /\d/i.test(event.key)" />
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 23 '23 at 08:23
  • Short and precise answer – akshay saxena Jun 09 '23 at 09:46
1

When using this code you cant use "BackSpace Button" in Mozilla Firefox you can only use backspace in Chrome 47 && event.charCode < 58;" pattern="[0-9]{5}" required>

1

http://www.texotela.co.uk/code/jquery/numeric/ numeric input credits to Leo Vũ for mentioning this and of course TexoTela. with a test page.

Clark Superman
  • 373
  • 2
  • 13
1

For general purpose, you can have JS validation as below:

It will work for Numeric keypad and normal number key's

function isNumberKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode

if (charCode < 31 || (charCode >= 48 && charCode <= 57 ) || (charCode >= 96 && charCode <= 105 ))
        return true;
    return false;
}

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
YasirPoongadan
  • 683
  • 6
  • 19
1

Yet another method that works pretty well.

<input type="text" name="celular" placeholder="Ej. 6756892" maxlength="8" id="telefono"   oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" >

What's great about this fix is that copy-pasted values are also included in the rule.

lfontana
  • 31
  • 6
1

You can use it by one line

<input onkeypress="return /[0-9]/i.test(event.key)" >
Siddhartha Mukherjee
  • 2,703
  • 2
  • 24
  • 29
0

It's better to add "+" to REGEX condition in order to accept multiple digits (not only one digit):

<input type="text" name="your_field" pattern="[0-9]+">

Dashko Leonid
  • 111
  • 1
  • 2
0

One way could be to have an array of allowed character codes and then use the Array.includes function to see if entered character is allowed.

Example:

<input type="text" onkeypress="return [45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57].includes(event.charCode);"/>
MA1
  • 2,767
  • 5
  • 35
  • 51
0

Use <input type="number">, it only accepts inputs that are numbers.
Try submitting the two forms below with non number values.

<form>
<!-- some code -->
 <input type="number">
 <button>SUBMIT</button>
 </form>

Older browsers don’t support type=number. So we can validate it with JavaScript:

<form onsubmit=
 "if (isNaN(document.getElementById('validatethis').value)) return false;">
<!-- some code -->
 <input type="text" id="validatethis">
 <button>SUBMIT</button>
 </form>
UserName Name
  • 267
  • 2
  • 3
0

The accepted answer is already good, however if your requirement is that you would like your user to be able to navigate their input (by using either the left or right cursor keys) and possibly amend their input (by using either the delete or the backspace key on the keyboard), you may choose to use this method.

Another benefit of this method is that accepts numbers from both the top row of the keyboard in addition to numbers from the numeric keypad.

The input HTML element will look something like this...

<input type="number"
  onkeydown="return validateIsNumericInput(event)"
  ...
  any other attributes for the input element
>

The JavaScript function will look like this:

/**
Checks the ASCII code input by the user is one of the following:
    - Between 48 and 57: Numbers along the top row of the keyboard
    - Between 96 and 105: Numbers in the numeric keypad
    - Either 8 or 46: The backspace and delete keys enabling user to change their input
    - Either 37 or 39: The left and right cursor keys enabling user to navigate their input
 */

function validateIsNumericInput(evt) {
    var ASCIICode = (evt.which) ? evt.which : evt.keyCode
    permittedKeys = [8, 46, 37, 39]
    if ((ASCIICode >= 48 && ASCIICode <= 57) || (ASCIICode >= 96 && ASCIICode <= 105)) {
        return true;
    };
    if (permittedKeys.includes(ASCIICode)) {
        return true;
    };
    return false;
}
Wayne Lambert
  • 576
  • 5
  • 9
0

From my understanding, you want to only allow numerical values in a text input box. I also struggled with this logic as I am a beginner. This problem can be simply solved in ES6.Here is the most simplest solution I came up with:

function test(){
    for (var i = 0; i < document.getElementById("element").value.length; i++) {
        if (isNaN(document.getElementById("element").value[i])){
            document.getElementById("element").value = '';
            console.log(document.getElementById("element").value[i])
        }
    };
}

Please note that this code does not work for floating-point-numbers!

coding4fun
  • 3,485
  • 1
  • 16
  • 28
0

This seems to work in Vue. Basically removes any non-digit input.

<input type="number" @input="(event) => event.target.value = event.target.value.replace(/\D/g, '')" />

It handles decimals, commas, strings, backspace, pasting, etc.

You can tweak the regex to allow decimals and commas too, though not sure how that would work properly with the browser locale.

Sebastiaan Luca
  • 486
  • 1
  • 8
  • 9