React js validation form

hi I have a problem with the control of the form and I need help to optimise it.

This is code 1 → https://github.com/patbi/reactjs-form-input-validation/blob/master/reactjs-form-input-validation.js

This is code 2 →

import React, { Component, Fragment  } from 'react'
import { Link } from 'react-router-dom';
import axios from 'axios';
import { NotificationContainer, NotificationManager } from 'react-notifications';


class Contact extends Component {
      constructor(props) {
      
      super(props)
        this.state = {
           fields: {},
           errors: {}
       }
    }

     handleValidation(){
        let fields = this.state.fields;
        let errors = {};
        let formIsValid = true;

        
        if(!fields["fullname"]){
           formIsValid = false;
           errors["fullname"] = "Cannot be empty";
        }

        if(typeof fields["fullname"] !== "undefined"){
           if(!fields["fullname"].match(/^[a-zA-Z]+$/)){
              formIsValid = false;
              errors["fullname"] = "Only letters";
           }        
        }

        
        if(!fields["email"]){
           formIsValid = false;
           errors["email"] = "Cannot be empty";
        }

        if(typeof fields["email"] !== "undefined"){
           let lastAtPos = fields["email"].lastIndexOf('@');
           let lastDotPos = fields["email"].lastIndexOf('.');

           if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
              formIsValid = false;
              errors["email"] = "Email is not valid";
            }
       }  

        if(!fields["subject"]){
           formIsValid = false;
           errors["subject"] = "Cannot be empty";
        }

        if(typeof fields["subject"] !== "undefined"){
           if(!fields["subject"].match(/^[a-zA-Z]+$/)){
              formIsValid = false;
              errors["subject"] = "Only letters";
           }        
        }


         if(!fields["message"]){
           formIsValid = false;
           errors["message"] = "Cannot be empty";
        }

        if(typeof fields["message"] !== "undefined"){
           if(!fields["message"].match(/^[a-zA-Z]+$/)){
              formIsValid = false;
              errors["message"] = "Only letters";
           }        
        }

       this.setState({errors: errors});
       return formIsValid;
   }

   contactSubmit(e){
        e.preventDefault();

         const contactObject = {
          fullname: this.state.fields["fullname"],
          email: this.state.fields["email"],
          subject: this.state.fields["subject"],
          message: this.state.fields["message"]
        };

        axios.post('/contact/create-contact/', contactObject)
          .then(res => {
            
        if(this.handleValidation()){
           NotificationManager.success('Merci de nous faire confiance, Nous revenons vers vous au plutôt', 'Successful!', 2000);
        }else{
           NotificationManager.error('error form!', 'errors');
        }
         })
    };

    handleChange(field, e){         
        let fields = this.state.fields;
        fields[field] = e.target.value;        
        this.setState({fields});
    }
    
   

    render() {
        return (
        <Fragment>

         <section className="saas_home_area">
            <div className="banner_top">
                <div className="container">
                    <div className="row">
                        <div className="col-md-12 text-center">
                            <h2 className="f_p f_size_40 l_height60 wow fadeInUp" data-wow-delay="0.3s" style={{fontSize:'30px'}}>Bonjour, comment <span className="f_700">peut-on vous aider</span><br /><span className="f_700">aujourd'hui ?</span></h2>
                            
                           
                        </div>
                    </div>
                    <div className="saas_home_img wow fadeInUp" data-wow-delay="0.8s">
                        <img src={require('../../images/nicole.png')} alt="" />
                    </div>
                </div>
            </div>
        </section>
      
            <section className="contact_info_area sec_pad bg_color">
            <div className="container">
                <div className="row">
                    <div className="col-lg-3 pr-0">
                        <div className="contact_info_item">
                            <h6 className="f_p f_size_20 t_color3 f_500 mb_20">Office Address</h6>
                            <p className="f_400 f_size_15">Complexe Beac Yaoundé, Cameroun</p>
                        </div>
                        <div className="contact_info_item">
                            <h6 className="f_p f_size_20 t_color3 f_500 mb_20">Contact Info</h6>
                            <p className="f_400 f_size_15"><span className="f_400 t_color3">Phone:</span> <a href="tel:698780156">(+237) 698 78 01 56</a></p>
                            <p className="f_400 f_size_15"><span className="f_400 t_color3">Fax:</span> <a href="tel:698780156">(+237) 698 78 01 56 </a></p>
                            <p className="f_400 f_size_15"><span className="f_400 t_color3">Email:</span> <a href="mailto:saasland@gmail.com">contactseedoc@gmail.com</a></p>
                        </div>
                    </div>
                    <div className="col-lg-8 offset-lg-1">
                        <div className="contact_form">
                            <form onSubmit= {this.contactSubmit.bind(this)} className="contact_form_box" method="post" id="contactForm" novalidate="novalidate">
                                <div className="row">
                                    <div className="col-lg-6">
                                        <div className="form-group text_box">
                                            <input type="text" onChange={this.handleChange.bind(this, "fullname")} value={this.state.fields["fullname"]} placeholder="Your Name" />
                                            <span style={{color: "red"}}>{this.state.errors["fullname"]}</span>
                                        </div>
                                    </div>
                                    <div className="col-lg-6">
                                        <div className="form-group text_box">
                                            <input type="text" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]} name="email" id="email" placeholder="Your Email" require="require" />
                                            <span style={{color: "red"}}>{this.state.errors["email"]}</span>
                                        </div>
                                    </div>
                                    <div className="col-lg-12">
                                        <div className="form-group text_box">
                                            <input type="text" onChange={this.handleChange.bind(this, "subject")} value={this.state.fields["subject"]} id="subject" name="subject" placeholder="Subject" />
                                            <span style={{color: "red"}}>{this.state.errors["subject"]}</span>
                                        </div>
                                    </div>
                                    <div className="col-lg-12">
                                        <div className="form-group text_box">
                                            <textarea onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]} name="message" id="message" cols="30" rows="10" placeholder="Enter Your Message . . ."></textarea>
                                            <span style={{color: "red"}}>{this.state.errors["message"]}</span>
                                        </div>
                                    </div>
                                </div>
                                <button type="submit" className="btn_three">Send Message</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </section>
  
      <NotificationContainer/>

        </Fragment>

                )
            }
        }

export default Contact;

Hi @Patrick_Biyaga,

Your question appears to be about using React and form input validation, but doesn’t currently have any direct relation to MongoDB.

While you may be able to get advice from some of the experienced developers in the MongoDB community, you’re likely to get faster advice on general React programming questions from Stack Overflow.

You should also provide more information on the problem you are trying to solve: what isn’t working with the current approach, what are you trying to optimise, and what have you tried so far.

Regards,
Stennie

Thanks for your feedback @Stennie_X , I’m using approach 2 at the moment and I managed to send the data to the database hosted on MongoDB Atlas. except that I have a problem with “empty form submission”, there is a good control of the fields but also submission and sending of an empty object. after that also I would like to empty the form fields as with approach 1. this is in short what I’m doing at the moment.

@Stennie_X I just solved my problem like this.

contactSubmit(e){
        e.preventDefault();
        let fields = this.state.fields;
         if(this.handleValidation(this.state.errors)){
          axios.post('/contact/create-contact/', fields)
          .then(res => {
         this.setState({fields});
         })
           NotificationManager.success('Merci de nous faire confiance, Nous revenons vers vous au plutôt', 'Successful!', 2000);
        }else{
           NotificationManager.error('error form!', 'errors');  
        }        
    };

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.