在React中验证电子邮件最简单,最短的方法是什么?

时间:2018-09-05 14:56:52

标签: javascript regex reactjs email-validation

我有一张注册表,我想用一种简单快捷的方法来验证电子邮件。

现在我正在像下面使用长正则表达式进行电子邮件验证。

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>
    );
  }
}
  • 在React中是否有最简单,最短的验证电子邮件的方法?

  • 使用 ES6 有什么更短的方法吗?

2 个答案:

答案 0 :(得分:1)

我在自己的项目中使用了这个简单的util函数:

export class AppComponent implements OnInit {
  name = 'Angular 5';

  selectedCountry: Country = new Country(2, 'Brazil');
  countries: Country[];
  states: State[];

  constructor(private selectService: SelectService) { }

  ngOnInit() {
    this.countries = this.selectService.getCountries();
    this.onSelect(this.selectedCountry.id);
  }

  onSelect(countryid) {
    this.states = this.selectService.getStates().filter((item) => item.countryid == countryid);
  }
}

这是通过Regular Expression完成的,如果输入是这样构造的,则返回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); } true

答案 1 :(得分:0)

这确实是验证电子邮件this GitHub issue的最简单方法 但是,由于您正在使用重要的ui组件,因此regex应该可以解决问题