Regex in React email validation

Another regex you can use which is a bit shorter is .+@.+\..+

It's not so strict but it checks the format which is the most important thing.


Maybe not perfect, customized @tw_hoff's post.

/.+@.+\.[A-Za-z]+$/.test("[email protected]") //true
/.+@.+\.[A-Za-z]+$/.test("[email protected]") //false

Use RegExp#test and fix the regex like this:

if (/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test($('#email').val())) { /* return true */ }
                               ^^^^^^^^^^^^  

To support multiple dots in the domain name, you may wrap the first part with a non-capturing group and set a 1 or more occurrences quantifier:

/^[a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/
               ^^^              ^^ 

The [A-z] actually matches some non letter symbols, and unescaped . matches any char but line break chars. Note that $ anchors the string at the end and + matches 1 or more occurrences.

There are other email regexps out there, see Validate email address in JavaScript? if your scenario differs from the one in OP.


Instead of using a regex, I suggest using a library called yup.

You can use as as follows:

import * as Yup from 'yup';

// here you can add multiple validations per field
const EmailSchema = Yup.object().shape({
  email: Yup.string().required('This field is mandatory').email('Enter a valid email'),
});

Inside your

{<Formik
  initialValues={this.state.form}
  validationSchema={EmailSchema}
  onSubmit={ values => {
    const data = {
      email: values.email
    };
  }}
>
{({handleSubmit, handleChange, values, touched, errors, isSubmitting}) => (
  <form onSubmit={handleSubmit} autoComplete="off" noValidate>
    <div className="form-group">
      <label htmlFor="id_email">Email <span>*</span></label>
      <input
        type="email"
        name="email"
        id="id_email"
        className={((errors.email && touched.email) ? 'is-invalid ' : '') + 'form-control'}
        autoComplete="off"
        value={values.email}
        onChange={handleChange}
      />
      {errors.email && touched.email && <div className="invalid-feedback">{errors.email}</div>}
    </div>
    <div className="row">
      <div className="col text-right">
        <button type="submit" name="btn-letsgo" disabled={isSubmitting} className="btn btn-primary">Submit</button>
      </div>
    </div>
  </form>
)}
</Formik>}