5

I have a problem with validation of HTML element input type="number" in ReactJS Application:

render() {
    return (
        <input type="number" onBlur={this.onBlur} />
    );
},

onBlur(e) {
    console.log(e);
}

The log is:

enter image description here

Everything is ok on desktop application, but on mobile there is a problem. User can change the keyboard and enter everything he wants. So I wanted to fix it using validation. When I try to catch the value the user enter, I get this log. It's like React is just hiding this incorrect value.

How can I fix it? Or there is another way how to validate input type="number" in ReactJS Application?

Thanks in advance.

2 Answers 2

3

It's the best way how to validate:

<input type="number" pattern="[0-9]*" inputmode="numeric">

In this way I can't enter smth else. Moreover e.target.value with checking on null can't get good fixed result because empty field and the field with not correct text are the same (empty).

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

1 Comment

"pattern: This attribute applies when the value of the type attribute is text, search, tel, url, email or password; otherwise it is ignored" via MDN
2

You can access the value through:

e.target.value;

I don't recall if on mobile if it passes an empty value if it's not a number like on desktop. But just do your checks against it. Don't let the form submit unless it's all valid :)

9 Comments

You can see from my screenshot, that e.target is null, so I can't get it.
Ah my bad. Typically one will update the stored value on a keyup change. Then you have a button to confirm the input.
I don't want to check in method onChange. By the way, onChange the same empty value like in onBlur
If you set a ref on the element: ref="myNumber" or w/e you wanna call it. You can access it through: React.findDOMNode(this.refs.myNumber). Should be able to access the value attribute from there.
With what value in the field though? Is it a number?
|

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.