如果其他组件始终运行其他条件

时间:2018-12-31 13:10:58

标签: javascript reactjs gatsby

我正在尝试建立联系表单,其中if else语句检查输入的电子邮件地址的有效性,然后嵌套(如果有嵌套)if else检查蜜罐文件是否具有值,并将ajaxj发布请求发送到aws api网关。 Ajax发布运行没有问题,但是外部的始终运行。

代码在这里:

import React from 'react'

import './style.scss'

const $ = require('jquery')
class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: '',
        email:'',
        subject:'',
        message:'',
        honeypot:'',
        result:'',
        alertType:'',
        formErrors:{
            email:'',
            name:'',
            message:''
        },
        isFormValid:false,
        emailValid:false,



    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleChange(event) {
    const target = event.target
    const value = target.value
    const name = target.name
    this.setState({ [name]: value })


  }



  handleSubmit(event) {
    event.preventDefault();
    var URL = "https://someaddress/";
    var form =this
    var data = {
        name: this.cleanInput(this.state.name.trim()),
        email: this.cleanInput(this.state.email.trim()),
        subject: this.cleanInput(this.state.subject.trim()),
        message: this.cleanInput(this.state.message.trim()),

    }
    this.validateField('email',data.email)

    data.message = "Bilgiler şunlar:\nAdı:"+data.name+"\nEmail Adresi: "+data.email+"\nKonu:"+data.subject+"\nMesaj:"+data.message
    data.subject = "[Bestpet Web Sitesinden Doldurulan Form] "+data.subject;
    data.email = "info@atlaspet.com.tr";
    if(this.state.emailValid ===true){
      if (this.state.honeypot=== ''){

         $.ajax({
           type: "POST",
           url: URL,
           dataType: "json",
           contentType: "application/json",
           data: JSON.stringify(data),
           success: function(){
            form.setState({name:'',email:'',message:'',subject:'',result:'Form başarıyla gönderildi.',alertType:'alert alert-success'})
           },
           error: function () {
             // show an error message
            form.setState({result: 'Sorunlar oluştu. Formu gönderemedik.',alertType:'alert alert-danger'});
           },
         });
        } else {console.log("Hi there, I guess you are not human baby");}
    } else { form.setState({result: 'Lütfen girmiş olduğunuz email adresini kontrol ediniz.',alertType:'alert alert-danger'})}
  }

 validateField(fieldName, value) {
    let fieldValidationErrors = this.state.formErrors;
    let emailValid = this.state.emailValid;
   ;

    switch (fieldName) {
      case 'email':
        emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        fieldValidationErrors.email = emailValid ? true : false;
        break;
      default:
        break;
    }
    this.setState({
      formErrors: fieldValidationErrors,
      emailValid: fieldValidationErrors.email
    }, this.validateForm);
    console.log(this)
  }

 validateForm() {
    this.setState({ isFormValid: this.state.emailValid });
  } 

 cleanInput(input){
    var search = [
      '<script[^>]*?>.*?</script>', // Strip out javascript
      '<[/!]*?[^<>]*?>', // Strip out HTML tags
      '<style[^>]*?>.*?</style>', // Strip style tags properly
      '<![sS]*?--[ \t\n\r]*>', // Strip multi-line comments
    ]
    var text = input
    // console.log(search.length)
    //var output = preg_replace($search, '', input);
    for (let i = 0; i < search.length; i++) {
      text = text.replace(new RegExp(search[i], 'gi'), '')
    }
    return text
  } 

  render() {
    return (

                      <form onSubmit={this.handleSubmit}>
                       <div>
                          <div className={"col-md-12 "+this.state.alertType}>{this.state.result!=='' && this.state.result}</div>
                          <input name="honeypot" type="text" style={{display:"none"}} value={this.state.honeypot} onChange={this.handleChange}/>
                       </div>
                               <div className="form-group">
                                     <div className="col-md-6">
                                                  <label>
                                                    Name:
                                                     {this.state.formErrors.name!=='' && <div className="col-md-12 alert alert-danger">'Sizinle iletişim kurabilmemiz için bir isim girmelisiniz'</div>}

                                                    <input name="name" type="text" value={this.state.name} className ="form-control required" onChange={this.handleChange} />
                                                  </label>
                                      </div>
                                     <div className="col-md-6">
                                                <label>
                                                email
                                                    <input type="text" name="email" className="form-control required" value={this.state.email} onChange={this.handleChange}/>
                                                </label>
                                      </div>
                               </div>                           



                                         <div className="form-group">
                                                <div className="col-md-12">
                                                        <label>
                                                        Subject
                                                            <input type="text" name="subject" className="form-control required" value={this.state.subject} onChange={this.handleChange}/>
                                                        </label>
                                                 </div>
                                         </div>
                                                <div className="form-group">
                                                    <div className="col-md-12">
                                                        <label>
                                                        Message
                                                            <textarea name="message" rows="6" className="form-control required" value={this.state.message} onChange={this.handleChange}/>
                                                        </label>
                                                    </div>
                                                </div>
                                              <div className="form-group">
                                                    <div className="col-md-12">         
                                                        <input type="submit" value="Submit" className="btn btn-sm btn-block btn-primary"/>
                                                    </div>
                                              </div>
                      </form>


    );
  }
}

export default ContactForm

我遇到问题的代码部分在handleSubmit函数中。 感谢您的提前帮助,祝大家新年快乐。

1 个答案:

答案 0 :(得分:0)

我已将有效性检查移至handleChange函数,并且现在可以按预期运行。 非常感谢!