【问题标题】:Regex in React email validationReact 电子邮件验证中的正则表达式
【发布时间】:2017-05-11 22:25:49
【问题描述】:

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

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;

【问题讨论】:

    标签: javascript regex reactjs


    【解决方案1】:

    使用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 中的不同,请参阅 Validate email address in JavaScript?

    【讨论】:

    • 尝试使用 RegExp 构造函数。
    • 想通了——最后只是丢失了):)
    • 我明白了,我专注于 test 周围的括号,并错过了 if 条件的括号,已修复。
    • @MewX 这不适用于该电子邮件,该修复适用于应该匹配xxx@xxxxxx.xxx 之类的电子邮件的/^[a-zA-Z0-9]+@+[a-zA-Z0-9]+.+[A-z]/ 模式。对于像您这样的电子邮件,您可以使用/^[a-zA-Z0-9]+@(?:[a-zA-Z0-9]+\.)+[A-Za-z]+$/
    • @WiktorStribiżew 感谢您的回复,是的,我知道。电子邮件模式实际上很棘手,有as.df@abc.com.au 之类的电子邮件:-/
    【解决方案2】:

    您可以使用的另一个较短的正则表达式是.+@.+\..+

    它不是那么严格,但它会检查最重要的格式。

    【讨论】:

      【解决方案3】:

      也许并不完美,定制了@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>}
        

        【讨论】:

          【解决方案5】:

          试试这个,很长,但应该适用于大多数电子邮件。

          ^[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,}$
          

          【讨论】:

            【解决方案6】:

            对我来说,它可以处理大多数电子邮件 ID, 希望对你有帮助

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

            【讨论】:

              【解决方案7】:
              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';
                  }
              }
              

              【讨论】:

                【解决方案8】:

                对我来说,这个正则表达式运行良好:

                ^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\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,}))$/
                

                所有学分: Alfred Ayi-bonte

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2014-04-14
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-05-11
                  • 2011-10-27
                  相关资源
                  最近更新 更多