APIs & Integrations

ashishkumar
Member

Prevent Form submission after successful Validation

Hi Team,

 

I want to add som custom validation on few fields. Also there are few action which I want to execute before form submit. So when use preventDefault under onFormSubit it didn't work.


hbspt.forms.create({
portalId: "****",
formId: "*****",
onFormSubmit: function($form, e) {
e.preventDefault();

}
});

 

 

0 Upvotes
3 Replies 3
jackcoldrick
HubSpot Employee
HubSpot Employee

Prevent Form submission after successful Validation

Hi @ashishkumar,

 

As outlined here: https://developers.hubspot.com/global-form-events it's not possible to prevent a form submission using the onFormSubmit callback. I would recommend attaching an event to the submit button within the "onFormReady" callback. You can see how I've handled this here. In my example I am using a regular expression to check an input before I submit the data.

 

 hbspt.forms.create({ 
                        portalId: "2990812",
                        formId: "c7782001-207b-408b-b009-4a57afed6056",
                        onFormReady: function($form, e) {
                            document.querySelector("[type='submit']").addEventListener("click", function(event) {
                                //if competition code doesn't contain 2 letters and 4 numbers then stop the form from submitting...
                                var code = $('input[name="competition_code"]').val();
                                var pattern = new RegExp('^MWL[0-9]{6}$', 'i');
								
                                if (pattern.test(code)) {
                                    console.log(code + " is valid");
                                } else {
                                    event.preventDefault();
                                    console.log(code + " is not valid");
                                    $('.alert').show();
                                    $('.userinput').html(code); 
                                }
                            }, false);
                        }
                    });

 

I hope this helps,

Jack

Jack Coldrick
Solutions Engineer @ HubSpot
Add me on LinkedIn
ChanduBobbili
Member

Prevent Form submission after successful Validation

Hi jackcoldrick....

 

when i use same code for my form, I'm getting error. I just replace portalid and formId

There was an error when running onFormReady function from hbspt.forms.create TypeError: Cannot read properties of null (reading 'addEventListener')

0 Upvotes
ashishkumar
Member

Prevent Form submission after successful Validation

Hi Jack

 

Thanks for your reply, I have tried same solution earlier and its not working. Strange thing is I have just copy and paste your code into my project and its also not working.

 

Thanks

0 Upvotes