Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate input type="number" in ReactJS?

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.

like image 755
Anatoli Avatar asked Sep 27 '22 01:09

Anatoli


1 Answers

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).

like image 126
Anatoli Avatar answered Oct 02 '22 16:10

Anatoli