Javascript 限制输入到文本框:只允许数字和小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2808184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restricting input to textbox: allowing only numbers and decimal point
提问by TinTin
How can I restrict input to a text-box so that it accepts only numbers and the decimal point?
如何限制文本框的输入,使其只接受数字和小数点?
回答by rebisco
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
This really works!
这真的有效!
回答by tau
form.onsubmit = function(){
return textarea.value.match(/^\d+(\.\d+)?$/);
}
Is this what you're looking for?
这是你要找的吗?
I hope it helps.
我希望它有帮助。
EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.
编辑:我编辑了上面的示例,以便只能有一个句点,前面至少有一位数字,后面至少有一位数字。
回答by Hassan Mokdad
The accepted solution is not complete, since you can enter multiple '.', for example 24....22..22. with some small modifications it will work as intended:
接受的解决方案并不完整,因为您可以输入多个“.”,例如 24....22..22。经过一些小的修改,它将按预期工作:
<html>
<head>
<script type="text/javascript">
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeypress="return isNumberKey(this, event);" />
</body>
</html>
回答by Kurenai Kunai
Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.
这是另一种解决方案,它允许使用十进制数并将小数点后的数字限制为小数点后两位。
function isNumberKey(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
return false;
else {
var len = $(element).val().length;
var index = $(element).val().indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">
回答by Hubert Grzeskowiak
All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1etc.
此处介绍的所有解决方案都使用单键事件。这很容易出错,因为输入也可以使用 copy'n'paste 或 drag'n'drop 给出。还有一些解决方案限制了非字符键的使用,例如ctrl+c,Pos1等。
I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.
我建议不要检查每个按键,而是检查结果是否符合您的期望。
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
if (validNumber.test(elem.value)) {
lastValid = elem.value;
} else {
elem.value = lastValid;
}
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>
The oninputevent is triggered just after something was changed in the text area and before being rendered.
该oninput事件在文本区域中的某些内容发生更改之后和呈现之前触发。
You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.
您可以将 RegEx 扩展为您想要接受的任何数字格式。这比检查单个按键更易于维护和扩展。
回答by Jitender Kumar
Just need to apply this method in Jquery and you can validate your textbox to just accept number with a decimal only.
只需要在 Jquery 中应用此方法,您就可以验证您的文本框以仅接受带小数的数字。
function IsFloatOnly(element) {
var value = $(element).val();
var regExp ="^\d+(\.\d+)?$";
return value.match(regExp);
}
Please see working demo here
请在此处查看工作演示
回答by lak-b
Are you looking for something like this?
你在寻找这样的东西吗?
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
</BODY>
</HTML>
回答by MonkeyZeus
For anyone stumbling here like I did, here is a jQuery 1.10.2 version I wrote which is working very well for me albeit resource intensive:
对于像我一样在这里磕磕绊绊的人,这是我编写的 jQuery 1.10.2 版本,尽管资源密集,但对我来说效果很好:
/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
var target = $(this);
var prev_val = target.val();
setTimeout(function(){
var chars = target.val().split("");
var decimal_exist = false;
var remove_char = false;
$.each(chars, function(key, value){
switch(value){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
if(value === '.'){
if(decimal_exist === false){
decimal_exist = true;
}
else{
remove_char = true;
chars[''+key+''] = '';
}
}
break;
default:
remove_char = true;
chars[''+key+''] = '';
break;
}
});
if(prev_val != target.val() && remove_char === true){
target.val(chars.join(''))
}
}, 0);
});
回答by Anish Karunakaran
A small correction to @rebisco's brilliant answer to validate the decimal perfectly.
对@rebisco 的精彩答案进行了小幅修正,以完美地验证小数点。
function isNumberKey(evt) {
debugger;
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
return false;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
回答by Rahul
If you want it for float values,
如果你想要它的浮点值,
Here is the function I am using
这是我正在使用的功能
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function check(e, value) {
//Check Charater
var unicode = e.charCode ? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)
if (unicode == 46) return false;
if (unicode != 8)
if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>
</HTML>

