繁体   English   中英

输入字段验证只接受逗号或点作为小数位

[英]Input field validation to accept only 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(/(,.*?),(.*,)?/, "$1");
    
    if (clean !== this.value) this.value = clean;
}

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

我设法通过检查 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM