javascriptreactjsreactjs.net

Form validation gets bypassed when I'm hitting the send button


I'm new to Reactjs and this is my first webapp created with it, so probably it is just a petty error this one I'm gonna ask you to help me with. Basically I'm trying to validate my form but it doesn't work. It doesn't matter if I fill the form or leave it blank, if I press the send button, it gets sent, complitely bypassing my validation system. This is my form component, I'm using emailjs to handle the email sending (it works perfectly). Also the state of the component gets updated without any problem, it's just the validation itself that gets bypassed. I hope you can help me:

class ContactForm extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        fields: { 'user_name': "", 'user_email': "" },
        errors: {}
    };
}

//Functions to handle form validation
handleValidation=()=> {
    let fields = this.state.fields;
    let errors = {};
    let formIsValid = true;

    //Name
    if (!fields["user_name"]) {
        formIsValid = false;
        errors["user_name"] = "Non può essere vuoto!";
        console.log("E' vuoto");
    }

    if (typeof fields["user_name"] !== "undefined") {
        if (!fields["user_name"].match(/^[a-zA-Z]+$/)) {
            formIsValid = false;
            errors["user_name"] = "Inserire solo lettere";
            console.log("Ci sono numeri");
        }
    }

    //Email
    if (!fields["user_email"]) {
        formIsValid = false;
        errors["user_email"] = "Non può essere vuoto!";
    }

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

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

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

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


sendEmail=(e)=> {
    let submitSuccess = document.getElementById('success');
    let submitFailed = document.getElementById('failed');
    let contactNumber = document.getElementById('contact_number');
    let userName = document.getElementById('user_name');
    let userMail = document.getElementById('user_email');
    let userMessage = document.getElementById('message');


    e.preventDefault();
    
    if (this.handleValidation) {
        //Generate random 5-digit number for the contact number
        contactNumber.value = Math.random() * 100000 | 0;

        emailjs.sendForm(/*Parameters to send email I'm not showing here*/)
            .then((result) => {
                console.log(result.text);
                submitSuccess.style.display = 'block';
            }, (error) => {
                console.log(error.text);
                submitFailed.style.display = 'block';
            })
    } else {
        alert("Ci sono errori nel form");
    };

}

render() {
    return (
        <form className="contact-form" onSubmit={this.sendEmail}>
            <input type="hidden" id="contact_number" name="contact_number" value="" />
            <label style={{ fontSize: '1.3em' }}>Nome</label>
            <input type="text" name="user_name" id="user_name" style={InputFormCSS} onChange={this.handleChange.bind(this, "user_name")} value={this.state.fields["user_name"]} required />
            <label style={{ fontSize: '1.3em' }}>Email</label>
            <input type="email" name="user_email" id="user_mail" style={InputFormCSS} onChange={this.handleChange.bind(this, "user_email")} value={this.state.fields["user_email"]} required />
            <label style={{ fontSize: '1.3em' }}>Message</label>
            <textarea name="message" id="message" style={TextareaFormCSS} required />
            <input type="submit" value="Invia" />
            <p id="success" style={{ display: 'none', backgroundColor: 'green', color: 'white', fontSize: '1.1em', borderRadius: 5, padding: 10 }}>Il messaggio è stato inviato con successo</p>
            <p id="failed" style={{ display: 'none', backgroundColor: 'red', color: 'white', fontSize: '1.1em', borderRadius: 5, padding: 10 }}>Non è stato possibile inviare il messaggio</p>
        </form>


    );
}

}


Solution

  • I fixed the problem by calling the validation function inside the sendmail function as parameter of the if statement and using its boolean returned value, like this:

    sendEmail=(e)=> {
    let submitSuccess = document.getElementById('success');
    let submitFailed = document.getElementById('failed');
    let contactNumber = document.getElementById('contact_number');
    let userName = document.getElementById('user_name');
    let userMail = document.getElementById('user_email');
    let userMessage = document.getElementById('message');
    
    
    e.preventDefault();
    
    if (this.handleValidation() == true) { ...