I’m working with a HubSpot form that validates company names. When users type a correct company name, it should redirect them to that company’s page. But when they enter a wrong or non-existent company name, it should show an error message instead.
The validation logic works perfectly and displays the right error messages. However, I can’t stop the form from actually submitting to HubSpot. Even when validation fails, the form still sends the data and shows the thank you page.
I’ve tried using return false and event.preventDefault() but neither approach works. The form uses AJAX for submission.
Here’s my JavaScript code:
$(document).ready(function() {
var companyName;
var companyValues = [];
var companyLinks = [];
var companyPrefixes = [];
$(".hs_organization input").on('input', function() {
companyName = $(this).val().replace(/\s+/g, '');
$('.form-container input[type=hidden]').val(companyName);
});
$(".form-container form").submit(function(event) {
event.preventDefault();
$('.hs_organization_list option').each(function() {
companyPrefixes.push($(this).text().substring(0, 3));
companyValues.push($(this).text().replace(/\s+/g, ''));
companyLinks.push($(this).val());
});
var namePrefix = companyName.substring(0, 3);
if ($.inArray(companyName, companyValues) !== -1) {
var matchIndex = $.inArray(companyName, companyValues);
setTimeout(function() {
window.location.href = companyLinks[matchIndex];
}, 1500);
return false;
} else if ($.inArray(namePrefix, companyPrefixes) > -1) {
$(".form-container .hs-button").before("<span>Please check company name spelling</span>");
return false;
} else {
$(".form-container .hs-button").before("<span>Organization not in our database</span>");
return false;
}
});
});
Any ideas on how to properly prevent the HubSpot form submission when validation errors occur?