CVO
CVO

Reputation: 742

Problem with HTML5 input type number dynamic validation with regex

I have a dynamic input generated with a simple jQuery(...).apend(...) that draw this code on my webpage:

<input type="number" name="19000003" min="0" max="99999999" required="" step="0.1"
oninput="/^(?:\d{0,8})(?:,\d{0,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0,-1);">

I can validate the first part (maximum size of characters including ','), but it gives me an error when y try to validate decimals.

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

When I test the regex code on the Chrome console it works (like these examples)

/^(?:\d{0,8})(?:,\d{0,3})?$/.test('1234,12');
/^(?:\d{0,8})(?:,\d{0,3})?$/.test('123,');

but doesn't works inside the input. What could I be doing wrong?

Upvotes: 0

Views: 1143

Answers (3)

Julio
Julio

Reputation: 5308

Your regexp does not work because you are trying to match a , on the input. However, even if you see a , on the browser, internally It is stored as . (probably to avoid the sort of problems you are facing now when the browser uses different locales)

So use /^\d{1,8}(?:\.\d{1,3})?$/ for your regex instead.

Here I leave a demo of the code. I have added an alert for every keypress so you can see how It is stored. Try to write 1,1 and see what happens.

<input type="number" name="19000003" min="0" max="99999999" required="" step="0.1"
oninput="alert(this.value); /^\d{1,8}(?:\.\d{1,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0,-1);">

Upvotes: 2

Renan Vizza Campos
Renan Vizza Campos

Reputation: 66

In addition to Julio's answer

note that step="0.1" can also break your form validation.

It's better to adhere to your regex validation (for 3 decimals, step="0.001")

More info here

Upvotes: 1

Vadim Hulevich
Vadim Hulevich

Reputation: 1833

try to separate function from element

    const myElement = document.getElementById("someInput");
    myElement.oninput = function(ev) {
        /^(?:\d{0,8})(?:,\d{0,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0, -1);
    }
    <input type="number" id="someInput" name="19000003" min="0" max="99999999" required="" step="0.1" />

Upvotes: 0

Related Questions