Home > database >  Html Input accept either comma or dot as decimal place
Html Input accept either comma or dot as decimal place

Time:09-25

I would like to add a validation for an html input to accept only numbers, a comma or a decimal. This is for EU based prices where a user would like to enter a price in the format of 3,22 or 3.22. Both should be allowed. But the user cannot enter a combination of both decimal or comma. I would like to handle this using regex as I find it most suitable. This is what I could find.

  <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

$(".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

CodePudding user response:

I managed to get it to work a different way by checking charCode and also a keyup function to replace the dot with comma.

    <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(".", ",");
        }
    }
  • Related