ReactJS中的电子邮件验证无法正常工作

时间:2018-11-19 15:36:47

标签: javascript regex reactjs state

我有onSubmit函数在响应中,添加了一些if / else语句来验证我的输入,一切工作正常,但不能发送电子邮件。它一直说我输入了错误的电子邮件地址。

还可以查看我的代码以检查是否可以将其写得更短吗?

  onSubmit = (e) => {

const { firstName, lastName, email, eventDate, validation, errorMessage} = this.state
if (firstName, lastName, eventDate, email) {
  this.setState({validation: true})
} else {
  this.setState({validation: false});
  this.setState({errorMessage: 'Please fill in all fields'})
  console.log(errorMessage);
}

if (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/.test(email)) {
  this.setState({validation: true})
} else {
  this.setState({validation: false});
  this.setState({errorMessage: 'Please enter correct email adress'})
  console.log(errorMessage);
}

if (validation) {
  const newEvent = {
    firstName: this.state.firstName,
    lastName: this.state.lastName,
    email: this.state.email,
    eventDate: this.state.eventDate
  }

  this.props.addEvent(newEvent);

  this.setState({
    firstName: '',
    lastName: '',
    email: '',
    eventDate: ''
  });
}

e.preventDefault();
}

3 个答案:

答案 0 :(得分:0)

请在下面找到用于电子邮件验证的示例:

console.log(new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test('sddsfdgsg'))
console.log(new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test('arulgetsolute@gmail.com'))
console.log(new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test('arulgetsolute@gmail.'))

答案 1 :(得分:0)

您需要指定case insensitive匹配项(只需将字母'i'添加到正则表达式中即可),如下所示:

if (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) {

现在您应该正确输入大写和小写字母。

答案 2 :(得分:0)

您可以使用https://www.npmjs.com/package/validator为您处理所有这些。

import validator from 'validator';
validator.isEmail(value)