The example for check valid email format in React

With this example, you can check user input their email is valid or invalid:


Copy this function into your Javascript file:

function isEmailCheck(email) {
  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,}))$/;
  return email ? re.test(String(email).toLowerCase()) : false;
}
Copy this code


Usage in your component:

 
import React, { Component } from "react";
import ReactDOM from "react-dom";
import isEmailCheck from 'isEmailCheck';

class App extends Component {
  state = {
    isEmail: false
  };
  checkEmail = e => {
    const email = e.target.value;
    const isEmail = isEmailCheck(email);
    this.setState({ isEmail });
  };

  render() {
    const { isEmail } = this.state;
    return (
      <div className="App">
        <div>
          Enter your email: <input onChange={this.checkEmail} type="text" />
        </div>
        <h2>{isEmail ? "Is email" : "Email is invalid"}</h2>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Copy this code


© 2019 4codev

Created with love by Sil.