0

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?

3 Answers 3

2

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);">

Sign up to request clarification or add additional context in comments.

1 Comment

Oh ok I understand. Thanks you very much. I spent a lot of time without considering that point.
1

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

1 Comment

That's true I'll adapt that part too. Lots of thanks
0

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" />

2 Comments

Hi, thanks for the response, but doesn't works too and the idea is to have it dynamic without external functions, but thanks
While that is a good practice, It has nothing to do about what OP asked...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.