@
@
@Richswitch2018-07-26 07:18:18
JavaScript
@Richswitch, 2018-07-26 07:18:18

How to bypass React's state feature for input validation?

Hey!
Off . In the React docs, you can find an example of how onChange works with inputs -> codepan.
You can see that onChange does not return the currently entered character in the event .
In my example, this bothers me because I am validating the user's mail with a regular expression.
those. when I entered the input, [email protected]I need to call the onChange event again for the validation to work.

handleChange(e) {
    this.validate(e.target.value);
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Zharov, 2018-07-26
_

You may notice that onChange does not return the currently entered character in the event.

the event has the last entered character, it is not in the state immediately after calling setState
handleChange(event) {
    this.setState({value: event.target.value});
    console.log(this.state.value);
  }

the setState method is asynchronous, and it takes a callback as the second parameter;
if you do it like this, then everything will be fine
handleChange(event) {
    this.setState({value: event.target.value}, () => console.log(this.state.value));
  }

I don't see any problems with validation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question