【问题标题】:Html Input accept either comma or dot as decimal placeHtml Input 接受逗号或点作为小数位
【发布时间】:2021-11-13 23:19:08
【问题描述】:

我想为 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(/(,.*?),(.*,)?/, "$1");
    
    if (clean !== this.value) this.value = clean;
}

有没有办法可以使用类似的东西来满足我的要求?我对正则表达式不太熟悉

【问题讨论】:

    标签: javascript jquery regex validation input


    【解决方案1】:

    我通过检查 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(".", ",");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多