How to Perform Conditional Validation with a Serverless Function Before Submitting a HubSpot Form?

Hello everyone! I have a website built on the HubSpot CMS where I’ve added a HubSpot form. I’d like to run a validation process when the user clicks the submit button, which then triggers a serverless function. Depending on whether the validation passes or fails, I want to decide whether the form submission logic should proceed or not. Has anyone done this before or have any suggestions on how to set it up in HubSpot CMS? Any tips or best practices would be greatly appreciated!

Hi @FBoholm,

You could try to utilize the “onBeforeFormSubmit” event. This allows performing actions just before the form is submitted.

Here is an sample script:

<script>
window.addEventListener('message', function(event) {
 if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onBeforeFormSubmit') {
 event.preventDefault();

 // Example call to the serverless function
 fetch('/your-serverless-function-url', {
 method: 'POST',
 body: JSON.stringify(event.data.data),
 headers: {
 'Content-Type': 'application/json'
 }
 })
 .then(response => response.json())
 .then(data => {
 if (data.shouldSubmit) {
 // If function returns "shouldSubmit", submit the form
 event.data.form.submit();
 } else {
 // Don't submit form
 console.log('Form submission prevented based on serverless function response');
 }
 })
 .catch(error => {
 console.error('Error calling serverless function:', error);
 });
 }
});
</script>

Hope this helps!