-1

I'm looking to do a more comprehensive email validation than the one I currently have. If you take a look at my code, I'm only checking for @ symbol and ends in .com. Is there a more comprehensive validation check I can include into my current code configuration?

JS:

this.state = {
  inputs: {
    name: '',
    email: '',
    message: '',
  },
  errors: {
    name: false,
    email: false,
    message: false,
  },
};

handleOnChange = e => {

const { name, value } = e.target;

if (name === 'email') {
  this.setState({
    inputs: {
      ...this.state.inputs,
      [name]: value,
    },
    errors: {
      ...this.state.errors,
      email:
        (value.includes('@') && value.slice(-4).includes('.com'))
          ? false
          : true,
    },
  });
} else {
  this.setState({
    inputs: {
      ...this.state.inputs,
      [name]: value,
    },
    errors: {
      ...this.state.errors,
      [name]: false,
    },
  });
}

};

Eric Nguyen
  • 926
  • 3
  • 15
  • 37

1 Answers1

1

The best way to validate email is using regular expressions:

const emailRegEx = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

The above will match 99.99% of valid emails

Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • 1
    The "official" RFC 5322 regex (the one you show in your answer?) is listed at https://www.regular-expressions.info/email.html (great read) and at https://emailregex.com/#container among other places. – Stephen P Jun 26 '19 at 20:07
  • Thanks for the source – Dupocas Jun 26 '19 at 22:12