Irvan Hilmi
Irvan Hilmi

Reputation: 491

Regex Issues - Trying to turn general number into currency

I have problem using match(/.{1,3}/gi) or match(\/d{1,3}/g) to split a string into 3 digits array each.

if(me.iselement(finppnr.inpprice)) {
    finppnr.inpprice.addEventListener("keyup", function() {
        let raw, ret;
        raw = finppnr.inpprice.value.split(".");
        raw = raw.join("").toString();
        if(raw.length > 0) {
            ret = raw.split("").reverse().join("").match(/.{1,3}/gi);
            ret = ret.join(".").split("").reverse().join("");
        }
        finppnr.inpprice.value = ret;
    });
}

here the HTML.

<div class="formcol">
    <div class="label">Item Price</div>
    <div class="field">
        <input class="inpprice finp" type="number">
    </div>
</div>

everything that i input into finppnr.inpprice larger then 1.000.000 will return an warning like this

The specified value "1.231.231" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

And the finppnr.inpprice.value suddenly became '' (empty). Meanwhile using the string straight, doesn't return any warning or error.

ret = "52990000".split("").reverse().join("").match(/.{1,3}/gi);
ret = ret.join(".").split("").reverse().join("");

I newer at this regular expression and just don't yet understand how actually the regular expression work. Please help

Upvotes: 0

Views: 53

Answers (1)

Avius
Avius

Reputation: 6244

Your problem is not with the regex, it's that you are using a number input and giving it a value like 52.990.000, which is not a valid number at all!

Number inputs are not able to interpret grouping separators, such as , or ., so numbers like 52,990,000, 52,990.999, etc. are all invalid and the input will not be able to interpret and thus render them.

A number like 999.999, on the other hand, is valid, since the . here simply acts as a decimal point.

All in all, your regex is fine, you have a problem with using a number input.

One quick solution would be to switch to a type="text" input, it can display arbitrary symbols.

If you are determined on keeping the type="number" input, you will have to find another solution, which will probably include positioning a type="text" input on top of your type="number" input, so that it is able to display the value the way you expect it to.

Upvotes: 1

Related Questions