React Js - Unable to enter value in Input Field

393 Views Asked by At

I appreciate all of your idea in advance. My problem here is the input field of the email is not updating. Can anyone give me a solution?

<input
    type="text"
    placeholder="Enter Email "
    onChange={this.emailHandle}
    value={this.state.email}
/>

Event handler for the above input field is here:

emailHandle = (e) => {
    if (e.target.value !== "undefined") {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (pattern.test(e.target.value)) {
            console.log(e.target.value);
            this.setState({ email: e.target.value })
        }
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

What's the initial value of your component state? For one, if you're not initializing the email property on state to be an empty string, and it's undefined, you're blocking that state from ever updating with your undefined check. But you have a bigger problem than that. You're testing to see if the value of the input matches your email regex pattern. That won't ever work if you use that check to block setting state. onChange is going to fire every time the input value changes, and that means it's going to change one character at a time. So what's happening is the user types a character, the onChange fires, but it doesn't match your pattern, and you don't update state.

What you want to do is always update state and then handle this as validation to block submitting the form. Or you could show an error of some kind, but you need to always call setState with the new value on e.target.value.

0
On

The onChange event will never be validate by the regex cause it is called on each key typed. So you start typing [email protected], with the a but a does not pass the regex... so the state is not updated... so it's like you didn't type a.