使用 javascript 或 jquery 在文本字段中进行十进制验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18480658/
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
Decimal validation in the textfield using javascript or jquery
提问by abiansh
i Want to validate a text field in keyupevent .
我想在keyup事件中验证文本字段。
in the field it should accept money type decimal like
在该字段中,它应该接受货币类型十进制,例如
(12.23) (.23) (0.26) (5.09) (6.00)
(12.23) (.23) (0.26) (5.09) (6.00)
if i enter some wrong value then it should return to the previous value and remove the wrong one
如果我输入了一些错误的值,那么它应该返回到以前的值并删除错误的值
回答by Thank you
I think something like this might be your best bet
我认为这样的事情可能是你最好的选择
var isValidCurrency = function(str) {
var num = parseFloat(str);
return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};
Some tests
一些测试
isValidCurrency("1234.56"); // true
isValidCurrency("1234.565"); // false
isValidCurrency("1234"); // false
isValidCurrency("foo"); // false
回答by jeff
Try this:
试试这个:
function evMoneyFormat(evt) {
//--- only accepts accepts number and 2 decimal place value
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
if (!regex.test(key)) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
The control:
控制:
<input type='text' onkeyup='evMoneyFormat( e );'>
回答by zzlalani
You can use following Regex
您可以使用以下正则表达式
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
EDIT
编辑
Please note that if the numbers preceding dot (.) has limit of length to two then the code valid code is
请注意,如果点 (.) 前的数字长度限制为 2,则代码有效代码为
^(\d{0,2})(\.\d{2})$
else if there is no limit then just remove the 2
from the code i.e.
否则,如果没有限制,则只需2
从代码中删除,即
^(\d{0,})(\.\d{2})$
回答by Rejayi CS
Try following code
试试下面的代码
function validateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
And in html
在 html 中
<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />