如何使HTML输入标签只接受数值?

时间:2022-11-25 11:21:14

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?

是否有一种简洁的方法来实现这一点?

19 个解决方案

#1


208  

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

您可以使用HTML5输入类型号来限制数字条目:

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

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

这只适用于HTML5的投诉浏览器。确保您的html文档的doctype是:

<!DOCTYPE html>

< !DOCTYPE html >

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

在旧的浏览器中,还可以看到https://github.com/jonstipe/digital polyfill以获得透明的支持。

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

一般情况下,您可以使用JS验证如下:

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条件,用这个:

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

Source: HTML text input allows only numeric input

源:HTML文本输入只允许数字输入。

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

JSFiddle演示:http://jsfiddle.net/viralpatel/nSjy7/

#2


20  

You can also use the pattern attribute in html5:

你也可以在html5中使用pattern属性:

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

http://www.pageresource.com/html5/input-validation-tutorial/

http://www.pageresource.com/html5/input-validation-tutorial/

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

虽然,如果您的doctype不是html,那么我认为您需要使用一些javascript/jquery。

#3


5  

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

您可以使用。这将只允许数字输入到输入框。

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

例如:http://jsfiddle.net/SPqY3/

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

请注意,输入类型=“number”标记只在较新的浏览器中支持。

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

对于firefox,您可以使用javascript验证输入:

http://jsfiddle.net/VmtF5/

http://jsfiddle.net/VmtF5/

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

更新2018-03-12:浏览器支持现在更好了,支持如下:

  • Chrome 6+
  • Chrome 6 +
  • Firefox 29+
  • Firefox 29 +
  • Opera 10.1+
  • Opera 10.1 +
  • Safari 5+
  • Safari 5 +
  • Edge
  • 边缘
  • (Internet Explorer 10+)
  • (ie 10 +)

#4


4  

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 : "#" & "$" & "%"
            else if (e.shiftKey && (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);" />

#5


3  

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

onkeyup triggers when the key is released.

当密钥被释放时,onkeyup触发。

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

isNaN(parseFloat(值))?检查输入值是否不是数字。

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

如果它不是一个数值,那么它的值将被设置为1000:如果它是一个数值,那么它的值就会被设置为值。

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

注意:由于某些原因,它只适用于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!

享受吧!

#6


3  

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

我和这个吵了一架。这里和其他地方的许多解决方案似乎都很复杂。这个解决方案使用jQuery/javascript以及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.

在我的例子中,我跟踪的是最小值为1的小数量,因此输入标签中的min=“1”,isNaN()检查中的abc = 1。对于纯正数,您可以将这些值更改为0,甚至只需从输入标记中删除min=“1”,以允许使用负数。

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.

同样,这也适用于多个盒子(通过id可以节省一些加载时间),只要在需要的地方添加“validateNumber”类就可以了。

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!

parseInt()基本上完成了您需要的工作,除了它返回NaN而不是某个整数值。使用一个简单的if(),您可以在所有返回NaN的情况下设置您喜欢的“回退”值:-)。这里还有W3状态,在检查之前,global版本的NaN将会类型转换,这将提供一些额外的打样(Number.isNaN()不这样做)。发送到服务器/后端的任何值都应该在那里进行验证!

#7


3  

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.

它会正常工作。

#8


2  

<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />

and in the js:

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

注意:跨浏览器和正则表达式。

#9


2  

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.

如果你可以使用HTML5,你可以使用,如果不能,你必须使用javascript来完成,就像你说的,它不会被submited后面的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

P。it’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’

#10


1  

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

使用怎么样?

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

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

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

另外,这里有一个问题,它有一些使用Javascript进行验证的例子。

Update: linked to better question (thanks alexblum).

更新:链接到更好的问题(谢谢alexblum)。

#11


1  

if not integer set 0

如果不是整数,则设置为0

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

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

#12


1  

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.

它是好的,但不是完美的。这对我来说是可行的,但我得到一个警告,即if语句可以简化。

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

我会评论原来的帖子,但我的名声太低了,无法评论(刚刚创建了这个账号)。

#13


1  

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

您可以使用属性类型='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.

这个输入字段只允许数值。您还可以指定该字段应该接受的最小值和最大值。

#14


1  

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:

请参阅我的项目,跨浏览器过滤器的价值文本输入元素在您的网页上使用JavaScript语言:输入关键字过滤器。您可以将该值过滤为整数、浮点数或编写自定义筛选器,例如电话号码筛选器。参见输入整数的代码示例:

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

还可以查看我的页面“Integer field:”,这是输入键过滤器的示例

#15


0  

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>

#16


0  

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>

使用此代码时,您不能在Mozilla Firefox中使用“BackSpace按钮”,您只能在Chrome 47 &&事件中使用BackSpace按钮。< 58;" pattern="[0-9]{5}"要求>

#17


0  

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.

http://www.texotela.co.uk/code/jquery/numeric/数字输入抵免Leo Vũ提及这当然TexoTela。测试页面。

#18


0  

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

一般情况下,您可以使用JS验证如下:

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

#19


-1  

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

最好在REGEX条件中添加“+”,以便接受多个数字(不只是一个数字):

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

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

#1


208  

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

您可以使用HTML5输入类型号来限制数字条目:

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

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

这只适用于HTML5的投诉浏览器。确保您的html文档的doctype是:

<!DOCTYPE html>

< !DOCTYPE html >

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

在旧的浏览器中,还可以看到https://github.com/jonstipe/digital polyfill以获得透明的支持。

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

一般情况下,您可以使用JS验证如下:

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条件,用这个:

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

Source: HTML text input allows only numeric input

源:HTML文本输入只允许数字输入。

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

JSFiddle演示:http://jsfiddle.net/viralpatel/nSjy7/

#2


20  

You can also use the pattern attribute in html5:

你也可以在html5中使用pattern属性:

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

http://www.pageresource.com/html5/input-validation-tutorial/

http://www.pageresource.com/html5/input-validation-tutorial/

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

虽然,如果您的doctype不是html,那么我认为您需要使用一些javascript/jquery。

#3


5  

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

您可以使用。这将只允许数字输入到输入框。

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

例如:http://jsfiddle.net/SPqY3/

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

请注意,输入类型=“number”标记只在较新的浏览器中支持。

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

对于firefox,您可以使用javascript验证输入:

http://jsfiddle.net/VmtF5/

http://jsfiddle.net/VmtF5/

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

更新2018-03-12:浏览器支持现在更好了,支持如下:

  • Chrome 6+
  • Chrome 6 +
  • Firefox 29+
  • Firefox 29 +
  • Opera 10.1+
  • Opera 10.1 +
  • Safari 5+
  • Safari 5 +
  • Edge
  • 边缘
  • (Internet Explorer 10+)
  • (ie 10 +)

#4


4  

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 : "#" & "$" & "%"
            else if (e.shiftKey && (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);" />

#5


3  

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

onkeyup triggers when the key is released.

当密钥被释放时,onkeyup触发。

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

isNaN(parseFloat(值))?检查输入值是否不是数字。

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

如果它不是一个数值,那么它的值将被设置为1000:如果它是一个数值,那么它的值就会被设置为值。

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

注意:由于某些原因,它只适用于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!

享受吧!

#6


3  

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

我和这个吵了一架。这里和其他地方的许多解决方案似乎都很复杂。这个解决方案使用jQuery/javascript以及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.

在我的例子中,我跟踪的是最小值为1的小数量,因此输入标签中的min=“1”,isNaN()检查中的abc = 1。对于纯正数,您可以将这些值更改为0,甚至只需从输入标记中删除min=“1”,以允许使用负数。

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.

同样,这也适用于多个盒子(通过id可以节省一些加载时间),只要在需要的地方添加“validateNumber”类就可以了。

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!

parseInt()基本上完成了您需要的工作,除了它返回NaN而不是某个整数值。使用一个简单的if(),您可以在所有返回NaN的情况下设置您喜欢的“回退”值:-)。这里还有W3状态,在检查之前,global版本的NaN将会类型转换,这将提供一些额外的打样(Number.isNaN()不这样做)。发送到服务器/后端的任何值都应该在那里进行验证!

#7


3  

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.

它会正常工作。

#8


2  

<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />

and in the js:

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

注意:跨浏览器和正则表达式。

#9


2  

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.

如果你可以使用HTML5,你可以使用,如果不能,你必须使用javascript来完成,就像你说的,它不会被submited后面的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

P。it’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’

#10


1  

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

使用怎么样?

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

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

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

另外,这里有一个问题,它有一些使用Javascript进行验证的例子。

Update: linked to better question (thanks alexblum).

更新:链接到更好的问题(谢谢alexblum)。

#11


1  

if not integer set 0

如果不是整数,则设置为0

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

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

#12


1  

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.

它是好的,但不是完美的。这对我来说是可行的,但我得到一个警告,即if语句可以简化。

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

我会评论原来的帖子,但我的名声太低了,无法评论(刚刚创建了这个账号)。

#13


1  

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

您可以使用属性类型='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.

这个输入字段只允许数值。您还可以指定该字段应该接受的最小值和最大值。

#14


1  

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:

请参阅我的项目,跨浏览器过滤器的价值文本输入元素在您的网页上使用JavaScript语言:输入关键字过滤器。您可以将该值过滤为整数、浮点数或编写自定义筛选器,例如电话号码筛选器。参见输入整数的代码示例:

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

还可以查看我的页面“Integer field:”,这是输入键过滤器的示例

#15


0  

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>

#16


0  

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>

使用此代码时,您不能在Mozilla Firefox中使用“BackSpace按钮”,您只能在Chrome 47 &&事件中使用BackSpace按钮。< 58;" pattern="[0-9]{5}"要求>

#17


0  

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.

http://www.texotela.co.uk/code/jquery/numeric/数字输入抵免Leo Vũ提及这当然TexoTela。测试页面。

#18


0  

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

一般情况下,您可以使用JS验证如下:

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

#19


-1  

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

最好在REGEX条件中添加“+”,以便接受多个数字(不只是一个数字):

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

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