2016-12-27 1 views
3

전자 메일이 올바르지 않은 경우 오류를 설정하려고합니다. 문자열이 비어 있는지 확인하면 양식이 알맞은 메시지로 경고합니다. 그러나 전자 메일이 정규식과 일치하는지 확인하면 작동하지 않습니다. 어떤 아이디어?Regex에서 전자 메일 유효성 검사

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][email protected]+[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; 

답변

2

사용 RegExp#test이 같은 정규식을 수정 :

if (/^[a-zA-Z0-9][email protected][a-zA-Z0-9]+\.[A-Za-z]+$/.test($('#email').val())) { /* return true */ } 
           ^^^^^^^^^^^^ 

[A-z] 실제로 일부 비 문자 기호와 일치하고, . 일치하는 모든 문자하지만 줄 바꿈 문자를 이스케이프. $은 끝에 문자열을 고정하고 +은 1 회 이상 일치합니다.

Validate email address in JavaScript?

+0

React가 이것을 다음과 같이 변경했을 때 오류가 발생합니다. –

+0

RegExp 생성자를 사용해보십시오. –

+0

결국 그것을 잃어 버렸습니다.) –

0

이 정규식 참조, 거기에 다른 이메일 regexps '에있다가 충분하지 않습니다 : /^[a-zA-Z0-9][email protected][a-zA-Z0-9]+.[A -Za-z] + $/ 은 다음 예와 같이 다중 도메인 서버를 테스트하지 않습니다 : [email protected]

관련 문제