[英]Input field validation to accept only comma or dot as decimal place
I would like to add a validation for an html input to accept only numbers, a comma or a decimal.我想为 html 输入添加验证以仅接受数字、逗号或小数。 This is for EU based prices where a user would like to enter a price in the format of 3,22 or 3.22.
这是针对基于欧盟的价格,用户希望以 3,22 或 3.22 的格式输入价格。 Both formats should be allowed.
这两种格式都应该被允许。 But the user should not be able to enter a combination of both decimal and comma.
但是用户不应该能够输入小数点和逗号的组合。 I would like to handle this using regex as I find it most suitable.
我想使用正则表达式来处理这个问题,因为我觉得它最合适。
<input class="form-control price_field" type="text" id="article_selling_price" name="article_selling_price">
A JS code I found to handle only comma我发现只处理逗号的 JS 代码
$(".price_field").on("keyup", checkKey);
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "").replace(/(,.*?),(.*,)?/, "$1");
if (clean !== this.value) this.value = clean;
}
Is there a way I can use something similar to achieve my requirement?有没有办法可以使用类似的东西来实现我的要求? I am not so familiar with regex
我不太熟悉正则表达式
I managed to get it to work a different way by checking charCode and also a keyup function to replace the dot with comma.我设法通过检查 charCode 和 keyup function 将点替换为逗号,使其以不同的方式工作。
<input class="form-control price_field" onkeypress="return isNumberKey(this, event);" type="text" id="price_search" name="price_search">
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 44) {
//check if previously there was a decimal
if (txt.value.indexOf('.') > 0) {
return false;
}
//Check if the text already contains the , character
if (txt.value.indexOf(',') === -1) {
return true;
} else {
return false;
}
} else if(charCode == 46){
//check if previously there was a comma
if (txt.value.indexOf(',') > 0) {
return false;
}
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
}
return true;
}
$(".price_field").on("keyup", checkKey);
function checkKey() {
if (this.value.indexOf('.') > 0) {
this.value = this.value.replace(".", ",");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.