最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the simplest and shortest way for validating an email in React? - Stack Overflow

programmeradmin1浏览0评论

I have a registration form and I want to validate an email in simple and shorter way.

Right now I am doing email validation as like below with long regex.

import React, { Component } from 'react';
import TextField from 'material-ui/TextField';

const emailPattern = /^(([^<>()\[\]\\.,;:\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,}))$/;

export default class Register extends Component {
  constructor(props) {
    super(props);

    this.state = {
      emailError: '',
      email: ''
    };
  }

handleTouchTap = () => {
    if(this.state.email == '' || this.state.email == null){
      this.setState({
      emailError: "Email cannot be empty"
    });
    }
    else if (!emailPattern.test(this.state.email) && this.state.email.length > 0) {
      this.setState({
        emailError: "Enter a valid email"
      });
    }
    }else{

      let data = {};
      data.email = this.state.email;
      // this.props.registerUser(data);
    }
  };

  changeEmail = (evt) => {
    this.setState({
        email: evt.target.value
      });
  }

  render() {
    return (
      <div>
        <div className="module row" style={{display: 'flex'}}>
          <section className="section">
            <h1>Create an account</h1> 
            <h3>It's free and always will be!</h3>  
            <imports.TextField errorText={this.state.emailError} floatingLabelText="Email" hintText="Enter your email" value={this.state.email} onChange={this.changeEmail} name="email" /> 
          </section>
          <section className="section">
            <div className="feature-link-carousel-cell">
              <a href="/" data-ga-category="homepage" data-ga-lbl="marketing-whatsnew" data-ga-action="whats-new-click">
                <img width="960" data-original=".jpg" className="lazy lazy-loaded" src=".jpg" alt="Do Race &amp; Gender Play a Role in Salary Negotiations? A New Study Says Yes" style={{opacity: 1}}>
                </img>
              </a>
            </div>
          </section>
        </div>
      </div>
    );
  }
}
  • Is there any simplest and shortest way of validating an email in React?

  • Are there any shorter ways with ES6?

I have a registration form and I want to validate an email in simple and shorter way.

Right now I am doing email validation as like below with long regex.

import React, { Component } from 'react';
import TextField from 'material-ui/TextField';

const emailPattern = /^(([^<>()\[\]\\.,;:\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,}))$/;

export default class Register extends Component {
  constructor(props) {
    super(props);

    this.state = {
      emailError: '',
      email: ''
    };
  }

handleTouchTap = () => {
    if(this.state.email == '' || this.state.email == null){
      this.setState({
      emailError: "Email cannot be empty"
    });
    }
    else if (!emailPattern.test(this.state.email) && this.state.email.length > 0) {
      this.setState({
        emailError: "Enter a valid email"
      });
    }
    }else{

      let data = {};
      data.email = this.state.email;
      // this.props.registerUser(data);
    }
  };

  changeEmail = (evt) => {
    this.setState({
        email: evt.target.value
      });
  }

  render() {
    return (
      <div>
        <div className="module row" style={{display: 'flex'}}>
          <section className="section">
            <h1>Create an account</h1> 
            <h3>It's free and always will be!</h3>  
            <imports.TextField errorText={this.state.emailError} floatingLabelText="Email" hintText="Enter your email" value={this.state.email} onChange={this.changeEmail} name="email" /> 
          </section>
          <section className="section">
            <div className="feature-link-carousel-cell">
              <a href="https://www.glassdoor.com/blog/do-race-gender-play-a-role-in-salary-negotiations/" data-ga-category="homepage" data-ga-lbl="marketing-whatsnew" data-ga-action="whats-new-click">
                <img width="960" data-original="https://media.glassdoor.com/home/feature-link/reviews/iStock_81884597_MEDIUM.jpg" className="lazy lazy-loaded" src="https://media.glassdoor.com/home/feature-link/reviews/iStock_81884597_MEDIUM.jpg" alt="Do Race &amp; Gender Play a Role in Salary Negotiations? A New Study Says Yes" style={{opacity: 1}}>
                </img>
              </a>
            </div>
          </section>
        </div>
      </div>
    );
  }
}
  • Is there any simplest and shortest way of validating an email in React?

  • Are there any shorter ways with ES6?

Share Improve this question edited Sep 7, 2018 at 2:09 Abraham 9,8756 gold badges55 silver badges58 bronze badges asked Sep 5, 2018 at 14:56 Hemadri DasariHemadri Dasari 34k40 gold badges124 silver badges165 bronze badges 3
  • 7 <input type="email" /> – Roberto Zvjerković Commented Sep 5, 2018 at 14:57
  • No simple answer. There are many many different email regex around. Why? Because there are many many different email variations. – charlietfl Commented Sep 5, 2018 at 15:02
  • Highly recommend not to write your own regex to validate email addresses. It's pretty complicated, see for example a list of valid email addresses that your regex would need to support to work properly: github.com/hapijs/isemail/blob/master/test/tests.json . Just use a npm package like this one: npmjs.com/package/isemail – fabio.sussetto Commented Sep 5, 2018 at 17:20
Add a comment  | 

3 Answers 3

Reset to default 16

I use this simple util function in my own projects:

function validateEmail (email) {
  const regexp = /^(([^<>()[\]\\.,;:\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 regexp.test(email);
}

This is done with Regular Expression and will return true if the input is constructed like this: [email protected]

I used this simple code for email validation in react

function emailVerify(error ={}, values){
if(!values.email){
    error.email = toast.error("Email Required...!");
}else if(values.email.includes(" ")){
    error.email = toast.error("Wrong Email...!")
}else if(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)){
    error.email = toast.error("Invalid email address...!")
}
else if(values.email.length() < 0 ){
    error.email = toast.error("Invalid email address...!")
}

This really is the simplest way to validate email https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email But, since you are using material ui component, regex should do the trick

发布评论

评论列表(0)

  1. 暂无评论