0

Having this input:

const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

...

<input
   pattern={REGEX_EMAIL_VALIDATION}
   type="email"
   value={field.value || ''}
   onChange={(e) => handleChangeEmail(id, e)}
/>

I've tried like this but it seems to let any input, it doesn't verify the pattern.

I would like to show a message while the user types the input if the value is not correct. In this case - if it doesn't have email shape.

1
  • did you try out my answer? Consider giving some feedback Commented Jun 18, 2021 at 12:46

2 Answers 2

1

You can conditionaly render an error message based on testing against your regular expression (RegEx.test(value) ? true : false).

import { useState } from "react";

export default function App() {

  const [email, setEmail] = useState(""); // state value for email
  const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  const handleEmailChange = (e) => {
    setEmail(e.target.value); // set email to value from input
  }
  
  // render
  return (
    <div>
      <input name="email" value={email} onChange={handleEmailChange}></input>
      {
        REGEX_EMAIL_VALIDATION.test(email) ? <small>valid</small> : <small>invalid</small>
      }
      <p>{email}</p>
    </div>
  );
}

Try it out in this Sandbox.

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

Comments

0

Please try this

const re =
  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

const handleOnChange = (e) => {
  if (re.test(e.target.value)) {
    // this is a valid email address
    // call setState({email: email}) to update the email
    // or update the data in redux store.
  } else {
    // invalid email, maybe show an error to the user.
  }
};

Comments

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.