skip to Main Content

I’ve created a custom contact form for a website using WordPress.

All the fields are required to send the form. In case of an error, the validation is done in Javascript to avoid reloading the page. All the validation fields work fine less one, the checkbox.

The issue I guess is in the javascript where I tried to check if the checkbox has been checked or not.

The PHP function to create the form:

<?php
add_shortcode( 'contact-form', 'site_contact_form' );
function site_contact_form() {

    $validation_messages = [];
    $success_message = '';

    if ( isset( $_POST['contact_form'] ) ) {

        //Sanitize the data
        $firstname = isset( $_POST['firstname'] ) ? sanitize_text_field( $_POST['firstname'] ) : '';
        $surname = isset( $_POST['surname'] ) ? sanitize_text_field( $_POST['surname'] ) : '';
        $email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
        $phone = isset( $_POST['phone'] ) ? sanitize_text_field( $_POST['phone'] ) : '';
        $acceptance = isset( $_POST['acceptance'] ) ? sanitize_text_field( $_POST['acceptance'] ) : '';

        //Validate the data
        if ( strlen( $firstname ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un nombre.', 'sobrado' );
        }

        if ( strlen( $surname ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un apellido.', 'sobrado' );
        }

        if ( strlen( $email ) === 0 or
             ! is_email( $email ) ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un email válido.', 'sobrado' );
        }

        if ( strlen( $phone ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un teléfono.', 'sobrado' );
        }

        if ( strlen( $acceptance ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor marca la casilla.', 'sobrado' );
        }

        //Send an email to the WordPress administrator if there are no validation errors
        if ( empty( $validation_messages ) ) {

            //$mail    = get_option( 'admin_email' );
            $to    = '[email protected]';
            $subject = 'Nuevo mensaje de ' . $firstname .' '. $surname;
            $message = 'El email del cliente es: ' . $email;

            wp_mail( $to, $subject, $message );

            $success_message = esc_html__( 'Su mensaje ha sido enviado con éxito.', 'sobrado' );

        }

    }

    //Display the validation errors
    if ( ! empty( $validation_messages ) ) {
        foreach ( $validation_messages as $validation_message ) {
            echo '<div class="c-form__validation-message">' . esc_html( $validation_message ) . '</div>';
        }
    }

    //Display the success message
    if ( strlen( $success_message ) > 0 ) {
        echo '<div class="c-form__success-message">' . esc_html( $success_message ) . '</div>';
    }

    ?>

    <div id="validation-messages-container" class="c-form__validation"></div>

    <form id="contact-form" class="c-form__form" action="<?php echo esc_url( get_permalink() ); ?>" method="post">

        <input type="hidden" name="contact_form">

        <div class="c-form__section c-form__section--firstname">
            <label for="firstname" class="c-form__label"><?php echo esc_html( 'Nombre', 'sobrado' ); ?></label>
            <input type="text" id="firstname" class="c-form__input" name="firstname" placeholder="<?php echo esc_html( 'Nombre', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--surname">
            <label for="surname" class="c-form__label"><?php echo esc_html( 'Apellidos', 'sobrado' ); ?></label>
            <input type="text" id="surname" class="c-form__input" name="surname" placeholder="<?php echo esc_html( 'Apellidos', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--phone">
            <label for="phone" class="c-form__label"><?php echo esc_html( 'Telefóno', 'sobrado' ); ?></label>
            <input type="text" id="phone" class="c-form__input" name="phone" placeholder="<?php echo esc_html( 'Telefóno', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--email">
            <label for="email" class="c-form__label"><?php echo esc_html( 'Email', 'sobrado' ); ?></label>
            <input type="email" id="email" class="c-form__input" name="email" placeholder="<?php echo esc_html( 'Email', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--footer">
            <div class="c-form__section c-form__section--acceptance">
                <input type="checkbox" id="acceptance" class="c-form__checkbox" name="acceptance" value="Yes">
                <label for="acceptance" class="c-form__label c-form__label--acceptance"><?php echo esc_html( 'Al confirmar mis datos acepto la política de privacidad y términos y condiciones.', 'site' ); ?></label>
            </div>
            <input type="submit" id="contact-form-submit" class="c-form__submit" value="<?php echo esc_attr( 'Enviar', 'site' ); ?>">
        </div>

    </form>

    <?php
}
?>

The JS:

const contactFormSubmit = document.getElementById('contact-form-submit');

if(contactFormSubmit){

    contactFormSubmit.addEventListener('click', validateForm);

    function validateForm(event) {

        event.preventDefault();
        event.stopPropagation();

        // Name
        const firstname = document.getElementById('firstname') !== null ?
        document.getElementById('firstname').value :
        '';

        // Surname
        const surname = document.getElementById('surname') !== null ?
        document.getElementById('surname').value :
        '';

        // Phone
        const phone = document.getElementById('phone') !== null ?
        document.getElementById('phone').value :
        '';

        // Email
        const email = document.getElementById('email') !== null ?
        document.getElementById('email').value :
        '';      '';

        // Checkbox
        const acceptance = document.getElementById('acceptance') !== false ?
        document.getElementById('acceptance').value : 
        '';

        const validationMessages = [];
        if (firstname.length === 0) {
            validationMessages.push('Por favor introduzca un nombre.');
        }

        if (surname.length === 0) {
            validationMessages.push('Por favor introduzca un apellido.');
        }

        if (phone.length === 0) {
            validationMessages.push('Por favor introduzca un teléfono.');
        }

        if (email.length === 0 || !emailIsValid(email)) {
            validationMessages.push('Por favor introduzca un email válido.');
        }

        if (acceptance.checked == false) {
            validationMessages.push('Por favor marca la casilla.');
        }

        if (validationMessages.length === 0) {

            //Submit the form
            document.getElementById('contact-form').submit();

        } else {

            //Delete all the existing validation messages from the DOM
            const parent = document.getElementById('validation-messages-container');
            while (parent.firstChild) {
                parent.removeChild(parent.firstChild);
            }

            //Add the new validation messages to the DOM
            validationMessages.forEach(function(validationMessage, index) {

                //add message to the DOM
                const divElement = document.createElement('div');
                divElement.classList.add('validation-message');
                const node = document.createTextNode(validationMessage);
                divElement.appendChild(node);

                const element = document.getElementById('validation-messages-container');
                element.appendChild(divElement);

            });

        }

    }

    /**
    * A simple function that verify the email with a regular expression.
    *
    * @param email
    * @returns {boolean}
    */
    function emailIsValid(email) {

        const regex = /S+@S+.S+/;
        return regex.test(email);

    }
}

Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    With to the help of @mykaf and @Barmar, I rewrite the JS code for the checkbox. It now works perfectly.

    const acceptance = document.getElementById('acceptance').checked ? document.getElementById('acceptance').value : '';
    
    if (acceptance.length === 0) {
      validationMessages.push('Some text');
    }
    

  2. Here is a DRYer version with the checkbox test fixed

    I added the validation to the submit event where it belongs

    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; // less permissive
    const emailIsValid = (email) => regex.test(email);
    const fieldsToValidate = [
      { id: 'firstname', errorMessage: 'Por favor introduzca un nombre.' },
      { id: 'surname', errorMessage: 'Por favor introduzca un apellido.' },
      { id: 'phone', errorMessage: 'Por favor introduzca un teléfono.' },
      { id: 'email', errorMessage: 'Por favor introduzca un email válido.', validate: emailIsValid },
    ];
    
    
    
    // Function to validate form fields
    const validateForm = () => {
      const acceptance = document.getElementById('acceptance')?.checked || false;
      const validationMessages = [];
    
      // Loop over fields and validate
      fieldsToValidate.forEach(({ id, errorMessage, validate }) => {
        const value = document.getElementById(id)?.value.trim() || '';
        // If field is empty or custom validation fails, add an error message (you can do required too)
        if (!value || (validate && !validate(value))) {
          validationMessages.push(errorMessage);
        }
      });
    
      // Validate the checkbox separately
      if (!acceptance) {
        validationMessages.push('Por favor marca la casilla.');
      }
    
      return validationMessages; // Return validation messages
    }
    
    const  handleValidationResults = (validationMessages) => {
      const parent = document.getElementById('validation-messages-container');
    
      // Clear previous validation messages
      parent.innerHTML = '';
    
      if (validationMessages.length > 0) {
        // Display validation messages
        validationMessages.forEach((message) => {
          const divElement = document.createElement('div');
          divElement.classList.add('validation-message');
          divElement.textContent = message;
          parent.appendChild(divElement);
        });
      }
    }
    
    const contactForm = document.getElementById('contact-form');
    if (contactForm) {
      contactForm.addEventListener('submit', (event) => {
        const validationMessages = validateForm();
        if (validationMessages.length > 0) {
          event.preventDefault(); // Prevent form submission ONLY if there are validation errors
          handleValidationResults(validationMessages);
        } else {
          // Allow the submit if there are no errors and clear any previous messages
          handleValidationResults([]);
        }
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search