使用javascript或jquery在文本字段中进行十进制验证
我想验证keyup事件中的文本字段 在字段中,它应该接受货币类型,如十进制 (12.23) (.23) (0.26) (5.09) (6.00) 如果我输入了一些错误的值,那么它应该返回到上一个值并删除错误的值使用javascript或jquery在文本字段中进行十进制验证,javascript,jquery,Javascript,Jquery,我想验证keyup事件中的文本字段 在字段中,它应该接受货币类型,如十进制 (12.23) (.23) (0.26) (5.09) (6.00) 如果我输入了一些错误的值,那么它应该返回到上一个值并删除错误的值 function evMoneyFormat(evt) { //--- only accepts accepts number and 2 decimal place value var theEvent = evt || window.event; var ke
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();
}
}
控件:
<input type='text' onkeyup='evMoneyFormat( e );'>
您可以使用以下正则表达式
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
编辑
请注意,如果点(.)前面的数字长度限制为2,则代码为有效代码
^(\d{0,2})(\.\d{2})$
否则,如果没有限制,则只需从代码中删除2
,即
^(\d{0,})(\.\d{2})$
尝试以下代码
function validateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
和html格式
<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />
我想这可能是你最好的选择
var isValidCurrency = function(str) {
var num = parseFloat(str);
return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};
一些测试
isValidCurrency("1234.56"); // true
isValidCurrency("1234.565"); // false
isValidCurrency("1234"); // false
isValidCurrency("foo"); // false
这是你的要求,到目前为止你试过什么?如果您向我们展示代码,我会很容易指出错误。@abiansh当您说“它应该返回到以前的值”var theEvent=evt | | window.event;var key=theEvent.keyCode | | theEvent.which;key=String.fromCharCode(key);var regex=/^(\d{0,2})(\.\d{2})$/;//如果(!regex.test(key)){theEvent.returnValue=false;//---如果(!regex.test(key)){theEvent.preventDefault)theEvent.preventDefault()?需要在
00
之前添加
。不适用于边缘情况“00.00”。我认为多个前导零无效。@t.G,“123foo”不是有效货币isValidCurrency(“123foo”)
返回false
,这在本例中是合适的。@T.G如果您愿意,您可以删除您的注释,我将删除我的注释,以避免其他用户混淆。