Cannot stop submission during a JS validation
-
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!
- You must be logged in to reply to this topic.