簡體   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