React在React电子邮件验证中

时间:2016-12-27 16:11:10

标签: javascript regex reactjs

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

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;

8 个答案:

答案 0 :(得分:12)

使用.spec.unschedulable并像这样修复正则表达式:

RegExp#test

if (/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test($('#email').val())) { /* return true */ } ^^^^^^^^^^^^ 实际匹配一些非字母符号,而未转义[A-z]匹配任何字符,但换行符。请注意,.将字符串锚定在末尾,$匹配1次或多次。

还有其他电子邮件正则表达式,请参阅Validate email address in JavaScript?

答案 1 :(得分:4)

您可以使用的另一个短一点的正则表达式是import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns %matplotlib inline Wind = pd.read_csv('C:\WindData.csv') Wind = Wind.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False) #Drop the nan Wind.index = pd.to_datetime(Wind['Date']) Wind_Weekly = Wind['Date'].resample('W').sum()

不是很严格,但是会检查最重要的格式。

答案 2 :(得分:3)

也许不是完美的,定制了@tw_hoff的帖子。

/.+@.+\.[A-Za-z]+$/.test("rr@rr.com.tr") //true
/.+@.+\.[A-Za-z]+$/.test("rr@rr.co.tr2") //false

答案 3 :(得分:2)

这个正则表达式是不够的:/ ^ [ - zA-Z0-9] +@ [a-aAA-Z0-9] +。[A-Za-z] + $ / 不会测试多域服务器,如下例所示: dsdsds@dssssdssdsds.dsddssds.dss.dsdsd.dds。

答案 4 :(得分:2)

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

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

答案 5 :(得分:0)

建议不要使用正则表达式,而建议使用名为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>}

答案 6 :(得分:0)

请尝试很长时间,但可以在大多数电子邮件中使用。

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

答案 7 :(得分:0)

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';
    }
}