How to prevent HubSpot form from submitting when validation fails?

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?

This happens because HubSpot has its own event handlers on the form that run no matter what you do with preventDefault. Had the same issue last year - unbinding HubSpot’s default handlers works way better than trying to fight them. Use $(form).off('submit') before you add your custom handler, then manually trigger HubSpot’s submission once validation passes. You can hit HubSpot’s form API through window.hbspt.forms and call the submit method yourself. Way easier than battling HubSpot’s built-in stuff.

HubSpot forms can be a pain with this. Add e.stopImmediatePropagation() right after preventDefault - it’ll stop other event handlers from firing. Just make sure you bind your submit handler before HubSpot’s handlers load, or theirs will run first.