• Hi,

    I have the below form defined.

    I want the user to have to enter either a location-select value or a location-typed value. If they don’t, an error should display under the location-typed field.

    I want the user to have to enter either a work-select value or a work-typed value. If they don’t, an error should display under the work-typed field.

    I want the user to have to select a file attachment. If they don’t, an error should display under the “no file chosen” message which is under the Choose File button.

    Then, if any of those 3 error conditions have occurred, the form submission should prevented.

    I have been trying every code option I can find for 2 days and via 4 AI chatbots…but none work. The command event.preventDefault() is not preventing submission.

    I even simplified it to just check for the 2 location fields and though the message displayed, the form still submitted.

    Here is the Javacript for that simplified test:

    document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('wpcf7beforesubmit', (event) => {
    const form = event.target;
    const locationSelect = form.querySelector('[name="location-select"]');
    const locationTyped = form.querySelector('[name="location-typed"]');
    const workSelect = form.querySelector('[name="work-select"]');
    const workTyped = form.querySelector('[name="work-typed"]');

    if (!locationSelect.value && !locationTyped.value.trim()) {
    event.preventDefault();

    // Create and display error message
    const errorMessage = document.createElement('p');
    errorMessage.classList.add('wpcf7-not-valid-tip');
    errorMessage.textContent = 'Please select or type a location.';

    // Remove any existing error messages
    form.querySelectorAll('.location-error').forEach(el => el.remove());

    // Add error message after both fields
    locationTyped.parentNode.insertAdjacentElement('afterend', errorMessage);

    // Highlight fields
    locationSelect.classList.add('wpcf7-not-valid');
    locationTyped.classList.add('wpcf7-not-valid');

    // Scroll to the error message
    errorMessage.scrollIntoView({ behavior: 'smooth', block: 'center' });

    return false;
    }
    }, false);
    });

    Here is the form definition:

    Select Location:

    [select location-select "" "Miami" "Orlando" "Tampa" "Jacksonville"]

    Or Type Location:

    [text location-typed]

    Select Work Done:

    [select work-select "" "Bathroom Remodel" "Kitchen Remodel" "Roof Repair" "Painting" "Flooring"]

    Or Type Work Done:

    [textarea work-typed rows:4]

    Upload Picture or Video (25 MB Max):Choose File

    No file chosen

    [file upload-file filetypes:.jpg|.jpeg|.png|.gif|.mp4|.mov|.avi limit:25mb class:cf7-upload-input]

    [submit "Submit"]

    Thank you for any help!

Viewing 1 replies (of 1 total)
  • Thread Starter flatword

    (@flatword)

    Here is the most recent code that correctly displays an error for the appropriate field group, but does not prevent the submission of the form.

    JS for the validation:

    // Add the CSS
    const styleSheet = document.createElement('style');
    styleSheet.textContent =
    <br>.field-group-error {<br> color: #ff0000;<br> font-size: 14px;<br> font-weight: bold;<br> margin: 5px 0;<br> padding: 5px;<br> display: none;<br>}<br><br>.field-group {<br> position: relative;<br>}<br><br>.field-group.has-error {<br> border-color: #ff0000 !important;<br>}<br>;
    document.head.appendChild(styleSheet);

    jQuery(document).ready(function($) {
    // Add error message elements at the start of each field group
    $('.field-group').each(function() {
    $(this).prepend('<div class="field-group-error"></div>');
    });

    // Function to validate a group (location or work)
    function validateGroup(selectField, textField) {
    return selectField.val().trim() !== '' || textField.val().trim() !== '';
    }

    // Function to display error for a group
    function showError(group, message) {
    group.addClass('has-error')
    .find('.field-group-error')
    .text(message)
    .show();
    }

    // Function to clear error for a group
    function clearError(group) {
    group.removeClass('has-error')
    .find('.field-group-error')
    .hide();
    }

    // Function to perform validation
    function validateForm() {
    let isValid = true;
    const form = $('.wpcf7-form');

    // Validate location group
    const locationGroup = form.find('[name="location-select"]').closest('.field-group');
    if (!validateGroup(
    locationGroup.find('[name="location-select"]'),
    locationGroup.find('[name="location-typed"]')
    )) {
    showError(locationGroup, 'Select or enter a location!');
    isValid = false;
    } else {
    clearError(locationGroup);
    }

    // Validate work group
    const workGroup = form.find('[name="work-select"]').closest('.field-group');
    if (!validateGroup(
    workGroup.find('[name="work-select"]'),
    workGroup.find('[name="work-typed"]')
    )) {
    showError(workGroup, 'Select or enter a work description!');
    isValid = false;
    } else {
    clearError(workGroup);
    }

    // Validate file upload
    const uploadGroup = form.find('[name="upload-file"]').closest('.field-group');
    if (!uploadGroup.find('[name="upload-file"]')[0].files.length) {
    showError(uploadGroup, 'Select a file to upload!');
    isValid = false;
    } else {
    clearError(uploadGroup);
    }

    // Clear all errors before returning the validation result
    if (isValid) {
    $('.field-group-error').hide();
    $('.field-group').removeClass('has-error');
    }

    return isValid;
    }

    // Add validation to the form submission
    $(document).on('submit', '.wpcf7-form', function(e) {
    if (!validateForm()) {
    e.preventDefault();
    e.stopPropagation();
    }
    });

    // Real-time validation on change
    // $('.wpcf7-form').on('change', 'select, textarea, input[type="file"]', function() {
    // validateForm();
    // });
    });

    And here is the form definition:

    [response]

    <div class="field-group">
    <label for="location-select">Select Location:</label>
    [select location-select "" "Miami" "Orlando" "Tampa" "Jacksonville"]
    <label for="location-typed">Or Type Location:</label>
    [textarea location-typed rows:4]
    </div>

    <div class="field-group">
    <label for="work-select">Select Work Done:</label>
    [select work-select "" "Bathroom Remodel" "Kitchen Remodel" "Roof Repair" "Painting" "Flooring"]
    <label for="work-typed">Or Type Work Done:</label>
    [textarea work-typed rows:4]
    </div>

    <div class="field-group">
    <label>Upload Picture or Video (25 MB Max):</label>
    <div class="custom-upload-wrapper">
    <button type="button" class="custom-upload-button">Choose File</button>
    <span class="selected-file-name">No file chosen</span>
    [file upload-file filetypes:.jpg|.jpeg|.png|.gif|.mp4|.mov|.avi limit:25mb class:cf7-upload-input]
    </div>
    </div>

    [submit "Submit"]

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.