[英]Validate input with only number and decimal after dot
I'm trying to make a validation that must accept the decimal numbers with up to 3 fields. 我正在尝试进行验证,该验证必须接受最多包含3个字段的十进制数字。 The comma can only appear if you have at least one number entered
仅当您输入了至少一个数字时,才会出现逗号
Allow:
100,000 100000
1,0 1,0
1 1
1,00 1,00
Doesn't Allow:
,00 ,00
,150 ,150
,0 ,0
100 100 100 100
I tried it (I'm using React
to get the input value): 我尝试了(我正在使用
React
来获取输入值):
var code = (event.which) ? event.which : event.keyCode;
if (code !== 46 && (code < 48 || code > 57)) {
event.preventDefault();
}
So far, I have managed to limit only fields and the point. 到目前为止,我已经设法仅限制字段和重点。 But, it still allows
.000
and is not limited to 3 decimal places. 但是,它仍然允许
.000
并且不限于3个小数位。
How can I do this? 我怎样才能做到这一点?
-------------- UPDATE SOLUTION -------------- --------------更新解决方案--------------
I found this answer that solve my problem. 我找到了解决我问题的答案 。 Thank you so much for your help guys
非常感谢您的帮助
I am not sure I understood your question well (I can update my solution based on your input) but I think you need a regular expression to match your overall value, not the individual inputs: 我不确定我是否很好地理解了您的问题(我可以根据您的输入来更新我的解决方案),但是我认为您需要一个正则表达式来匹配您的总体价值,而不是单个输入:
function is_valid(value) {
var exp = /^\d+(,*\d+)?$/;
return exp.test(value)
}
tests = ["100,000", "1,0", "1", "1,00", ",00", ",150", ",0", "100 100"]
for(var i=0; i<tests.length; i++) {
console.log(tests[i], is_valid(tests[i]))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.