How to make HTML input tag only accept numerical values?

僤鯓⒐⒋嵵緔 提交于 2019-11-26 11:39:48
Viral Patel

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 purpose, you can have JS validation as below:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.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 condition" with this:

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

Source: HTML text input allow only numeric input

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/

martincarlin87

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.

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.

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+)
<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />

and in the 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 bu 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.

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

var userName = document.querySelector('#numberField');

userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {  
  var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
  this.value = newValue;
}
  
<input type="text" id="numberField">
<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 exiting, you can also have a boundary:

<input 
    onkeyup="value=isNaN(parseFloat(value))||value<0||value>9000?1000:value"
       type="number"
      value="1000"
>

Enjoy!

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

    <input type="number" min="1" class="validateNumber">

    $(document).on('change', '.validateNumber', function() { 
        var abc = parseInt($(this).val());
        if(isNaN(abc)) { abc = 1; }
        $(this).val(abc);
    });

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

Sameh Saeed

function AllowOnlyNumbers(e) {

    e = (e) ? e : window.event;
    var key = null;
    var charsKeys = [
        97, // a  Ctrl + a Select All
        65, // A Ctrl + A Select All
        99, // c Ctrl + c Copy
        67, // C Ctrl + C Copy
        118, // v Ctrl + v paste
        86, // V Ctrl + V paste
        115, // s Ctrl + s save
        83, // S Ctrl + S save
        112, // p Ctrl + p print
        80 // P Ctrl + P print
    ];

    var specialKeys = [
    8, // backspace
    9, // tab
    27, // escape
    13, // enter
    35, // Home & shiftKey +  #
    36, // End & shiftKey + $
    37, // left arrow &  shiftKey + %
    39, //right arrow & '
    46, // delete & .
    45 //Ins &  -
    ];

    key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

    //console.log("e.charCode: " + e.charCode + ", " + "e.which: " + e.which + ", " + "e.keyCode: " + e.keyCode);
    //console.log(String.fromCharCode(key));

    // check if pressed key is not number 
    if (key && key < 48 || key > 57) {

        //Allow: Ctrl + char for action save, print, copy, ...etc
        if ((e.ctrlKey && charsKeys.indexOf(key) != -1) ||
            //Fix Issue: f1 : f12 Or Ctrl + f1 : f12, in Firefox browser
            (navigator.userAgent.indexOf("Firefox") != -1 && ((e.ctrlKey && e.keyCode && e.keyCode > 0 && key >= 112 && key <= 123) || (e.keyCode && e.keyCode > 0 && key && key >= 112 && key <= 123)))) {
            return true
        }
            // Allow: Special Keys
        else if (specialKeys.indexOf(key) != -1) {
            //Fix Issue: right arrow & Delete & ins in FireFox
            if ((key == 39 || key == 45 || key == 46)) {
                return (navigator.userAgent.indexOf("Firefox") != -1 && e.keyCode != undefined && e.keyCode > 0);
            }
                //DisAllow : "#" & "$" & "%"
                //add e.altKey to prevent AltGr chars
            else if ((e.shiftKey || e.altKey) && (key == 35 || key == 36 || key == 37)) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
    else {
        return true;
       }
    }
<h1>Integer Textbox</h1>
    <input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" />

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)))" />
czioutas

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 doesnt get submited to do it from codebehind.

<input id="numbersOnly" onkeypress='validate()' />

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

P.S didnt test the code but it should be more or less correct if not check for typos :D 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 :D

dan1111

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

if not integer set 0

<input type="text" id="min-value" />

$('#min-value').change(function ()
            {   
                var checkvalue = $('#min-value').val();
                if (checkvalue != parseInt(checkvalue))
                    $('#min-value').val(0);
            });

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

Would comment the original post, but my reputation is too low to do so (just created this account).

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.

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

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

Plexis Plexis

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

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>

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>

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!