Html 输入接受逗号或点作为小数位
Html Input accept either comma or dot as decimal place
我想为 html 输入添加验证以仅接受数字、逗号或小数。这是针对基于欧盟的价格,用户希望以 3,22 或 3.22 的格式输入价格。两者都应该被允许。但用户不能输入小数或逗号的组合。
我想使用正则表达式来处理这个问题,因为我觉得它最合适。这是我能找到的。
<input class="form-control price_field" type="text" id="article_selling_price" name="article_selling_price">
我发现只处理逗号的 JS 代码
$(".price_field").on("keyup", checkKey);
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "").replace(/(,.*?),(.*,)?/, "");
if (clean !== this.value) this.value = clean;
}
有什么方法可以使用类似的东西来实现我的要求吗?我不太熟悉正则表达式
我通过检查 charCode 和用逗号替换点的 keyup 函数设法让它以不同的方式工作。
<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(".", ",");
}
}
我想为 html 输入添加验证以仅接受数字、逗号或小数。这是针对基于欧盟的价格,用户希望以 3,22 或 3.22 的格式输入价格。两者都应该被允许。但用户不能输入小数或逗号的组合。 我想使用正则表达式来处理这个问题,因为我觉得它最合适。这是我能找到的。
<input class="form-control price_field" type="text" id="article_selling_price" name="article_selling_price">
我发现只处理逗号的 JS 代码
$(".price_field").on("keyup", checkKey);
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "").replace(/(,.*?),(.*,)?/, "");
if (clean !== this.value) this.value = clean;
}
有什么方法可以使用类似的东西来实现我的要求吗?我不太熟悉正则表达式
我通过检查 charCode 和用逗号替换点的 keyup 函数设法让它以不同的方式工作。
<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(".", ",");
}
}