0

I have a bug in my application. It's a currency converting app - and it should only accept numbers.

I wrote an application that takes numbers from input. It works perfectly fine on Chrome, but firefox allows me/user to type in any character. I tried all kinds of methods, and functions to prevent this behavior - such as regex functions with tests to see if e.target.value is a number or not, pattern="[0-9]", inputype='numeric' and a few more.

<input type="number" onChange={e => setFromTo(e.target.value)} />

Does anybody know how to prevent firefox input field from accepting any character, and only taking in numbers?

2 Answers 2

1

try adding this to your input tag.

oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');"
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks for the idea - because of you I found the solution to this problem.
It works! Thanks. Can you give a small explanation of how it works tho?
I'm glad it worked for you! Here's how the code works: oninput listens for any changes in the input field and modifies this.value in real-time. this.value.replace(/[^0-9.]/g, '') removes any character that isn't a number (0-9) or a period (.), allowing only numbers and one decimal point. .replace(/(\..*?)\..*/g, '$1') ensures only one decimal point is allowed. If more than one decimal is entered, it keeps only the first occurrence. This way, Firefox is restricted to numeric input, just like in Chrome!
1

Try adding this line in your input field

onKeyPress={(event) => {(!/[0-9]/.test(event.key)) {
                            event.preventDefault();
                          }
                        }}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.