在React中使用正则表达式进行电子邮件验证

21
我想设置一个当电子邮件不正确时显示错误的功能。 当我检查字符串是否为空时,表单会弹出正确的消息。 但是当我检查电子邮件是否与正则表达式匹配时,它无法工作。 有任何想法吗?

我正在尝试设置在电子邮件不正确时触发错误的功能。当我检查字符串是否为空时,表单会弹出适当的消息。但是当我检查电子邮件是否与正则表达式匹配时,它不起作用。有什么想法吗?

import React, { Component } from 'react';
import { Link } from 'react-router';
// Our custom input component, which uses label, id and tabIndex properties
var MyInput = React.createClass({
  render: function() {

    // Get the error message by calling a function, passed to this
    // component through getError property
    var errorMessage = this.props.getError(this.props.id);

    return (
        <fieldset className={"form-fieldset ui-input first " + (errorMessage ?    "erroneous" : "")}>
            <input type="text" name={this.props.id} id={this.props.id} tabIndex={this.props.tabIndex} />
            <label htmlFor={this.props.id}>
              <span data-text={this.props.label}>{this.props.label}</span>
            </label>
            <span className="error">{errorMessage ? errorMessage : null}</span>
          </fieldset>
    )
  }
});

// Form
var SendForm = React.createClass ({
  getError: function (fieldName) {
    return this.state[fieldName+"Error"];
  },
  setError: function (fieldName, error) {
    var update = {};
    update[fieldName+"Error"] = error;
    this.setState(update);
  },
  getInitialState: function() {
    return {
      isMailSent: false,
      errorMessage: null,
    };
  },
  componentDidMount: function () {
    // This will be called right when the form element is displayed
    $('form').parsley()
  },
  validateForm: function(){
    var hasErrors = false;

    if ($('#company').val().length < 1){
      this.setError("company", "Please enter your company name");
      hasErrors = true;
    } else this.setError("company", null)

    if ($('#industry').val().length < 1){
      this.setError("industry", "Please enter the industry");
      hasErrors = true;
    } else this.setError("industry", null)

    if ($('#firstName').val().length < 1){
      this.setError("firstName", "Please enter your first name");
      hasErrors = true;
    } else this.setError("firstName", null)

    if ($('#lastName').val().length < 1) {
      this.setError("lastName", "Please enter your last name");
      hasErrors = true;
    } else this.setError("lastName", null)

    if ($('#email').val() == '') {
      this.setError("email", "Please enter your email address");
      hasErrors = true;
    } else this.setError("email", null)

    if ($('#email').val() !== /^[a-zA-Z0-9]+@+[a-zA-Z0-9]+.+[A-z]/) {
      this.setError("email", "Please enter a valid email address");
      hasErrors = true;
    } else this.setError("email", null)


    if ($('#phone').val().length < 1) {
      this.setError("phone", "Please enter your phone number");
      hasErrors = true;
    } else this.setError("phone", null)

    return !hasErrors;
  },
  handleSubmit: function (e) {
    e.preventDefault();

    // Check if data is valid
    if (!this.validateForm()) {
      //return if not valid
      return;
    }

    // Get the form.
    var form = $('form');

    // Serialize the form data.
    var formData = $(form).serialize();

    var self = this;
    console.log(formData)
    // Submit the form using AJAX.
    $.ajax({
      type: 'POST',
      url: 'email-handler.php',
      data: formData
    }).done(function(response) {

      // Update the state, notifying that mail was sent
      // This value will be used in the form when rendering
      self.setState({isMailSent: true})

      // Hide the form
      $('.formCont').hide();
    }).fail(function(data) {
      // Make sure that the formMessages div has the 'error' class.
      self.setState({errorMessage : "Something went wrong. Please try again."});
    });
  },
 render: function(){
   return (
     <div className="companyForm">

       <h2 className="header compFormHead">Form</h2>

       { this.state.isMailSent ?
           <div className="success">Thank you for submission. Someone will be in contact with you shortly.</div>
           : null }

       <div className="container formCont">
         <form method="post" acceptCharset="utf-8" autoComplete="off" onSubmit={this.handleSubmit}>

         <MyInput id="company" label="Company" tabIndex="1" getError={this.getError}/>
         <MyInput id="industry" label="Industry" tabIndex="2" getError={this.getError}/>

         <div className="two-column">
           <MyInput id="firstName" label="First Name" tabIndex="3" getError={this.getError}/>
           <MyInput id="lastName" label="Last Name" tabIndex="4" getError={this.getError}/>
         </div>
         <div className="two-column">
           <MyInput id="email" type="email" label="Email" tabIndex="5" getError={this.getError}/>
           <MyInput id="phone" label="Phone" tabIndex="6" getError={this.getError}/>
         </div>

         {this.state.errorMessage ? <div className="fail">{this.state.errorMessage}</div> : null}

         <div className="form">
           <input type="submit" name="submit" className="btn btn-primary" value="APPLY" tabIndex="7" />
         </div>

         </form>
       </div>

     </div>
   );
 }
});

export default SendForm;
11个回答

36

使用 RegExp#test 函数,并将正则表达式修正为以下形式:

if (/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test($('#email').val())) { /* return true */ }
                               ^^^^^^^^^^^^  
为了支持域名中的多个点,您可以使用非捕获组将第一部分括起来,并设置“一个或多个出现”量化器:

为了支持域名中的多个点,您可以将第一部分用非捕获组括起来,并设置“1个或多个出现”的量化器:

/^[a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/
               ^^^              ^^ 

[A-z]实际上匹配一些非字母符号,而未转义的.则匹配除换行符以外的任何字符。需要注意的是,$将字符串锚定在结尾处,+匹配1个或多个出现。

还有其他的邮箱正则表达式可用,如果您的场景与OP中的不同,请参见在JavaScript中验证电子邮件地址?


搞定了 - 最后只是缺少了一个 ) :) - Max T
1
我明白了,我关注的是 test周围的括号,而错过了if条件的括号,已经修复。 - Wiktor Stribiżew
1
@MewX 这个方法不适用于那种类型的电子邮件,修正的正则表达式是 /^[a-zA-Z0-9]+@+[a-zA-Z0-9]+.+[A-z]/,主要用来匹配像 xxx@xxxxxx.xxx 的电子邮件。对于像您这样的电子邮件,您可以使用 /^[a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/ - Wiktor Stribiżew
@WiktorStribiżew 感谢您的回复,是的我知道。电子邮件模式实际上相当棘手,有像 as.df@abc.com.au 这样的电子邮件 :-/ - MewX
@wiktorstribizew 谢谢回复,你说得对。它正在工作.. :) - Chandler Bing
显示剩余2条评论

7

你可以使用另一个比较简短的正则表达式:.+@.+\..+

它不是非常严格,但它检查了格式,这是最重要的事情。


7
也许不是完美的,定制化 @tw_hoff 的帖子。
/.+@.+\.[A-Za-z]+$/.test("rr@rr.com.tr") //true
/.+@.+\.[A-Za-z]+$/.test("rr@rr.co.tr2") //false

4

建议您使用名为 yup 的库,而不是使用正则表达式。

您可以按如下方式使用:

import * as Yup from 'yup';

// here you can add multiple validations per field
const EmailSchema = Yup.object().shape({
  email: Yup.string().required('This field is mandatory').email('Enter a valid email'),
});

在您的系统内部
{<Formik
  initialValues={this.state.form}
  validationSchema={EmailSchema}
  onSubmit={ values => {
    const data = {
      email: values.email
    };
  }}
>
{({handleSubmit, handleChange, values, touched, errors, isSubmitting}) => (
  <form onSubmit={handleSubmit} autoComplete="off" noValidate>
    <div className="form-group">
      <label htmlFor="id_email">Email <span>*</span></label>
      <input
        type="email"
        name="email"
        id="id_email"
        className={((errors.email && touched.email) ? 'is-invalid ' : '') + 'form-control'}
        autoComplete="off"
        value={values.email}
        onChange={handleChange}
      />
      {errors.email && touched.email && <div className="invalid-feedback">{errors.email}</div>}
    </div>
    <div className="row">
      <div className="col text-right">
        <button type="submit" name="btn-letsgo" disabled={isSubmitting} className="btn btn-primary">Submit</button>
      </div>
    </div>
  </form>
)}
</Formik>}

4
function isEmail(val) {
    let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
    if(!regEmail.test(val)){
      return 'Invalid Email';
    }
}

3

对我而言,这在大多数电子邮件ID上都有效, 希望能有所帮助。

  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/

2

试试这个,虽然有些冗长,但应该适用于大多数电子邮件。

^[a-z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1}([a-z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1})*[a-z0-9]@[a-z0-9][-\.]{0,1}([a-z][-\.]{0,1})*[a-z0-9]\.[a-z0-9]{1,}([\.\-]{0,1}[a-z]){0,}[a-z0-9]{0,}$

1

一种简单的解决方案:

这是我的TextField组件的外观:

            <TextField
              autoFocus
              defaultValue={user?.email}
              onChange={(e) => onSetValue(e, e.target.value)}
              required={field.required}
              fullWidth
              label={field.title || key}
              variant="outlined"
              inputProps={{
                className: classes.input,
                pattern: '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[.]{1}[a-zA-Z]{2,}$',
              }}
            />

1
对我来说,这个正则表达式运行良好:
^(([^<>()[\]\\.,;:\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 const EmailRegex=/^(([^<>()\[\]\\.,;:\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,}))$/

all credits to: Alfred Ayi-bonte


0

试一下

pattern: { value: /[a-zA-Z][a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/, message: 'Please enter a valid email' },

[a-zA-Z][a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接