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();
}
});
As outlined here: Accounts Dashboard | HubSpot 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);
}
});
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.
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’)
For those combing through threads trying to find a solution, the onFormReady function seems to only work with jQuery. So make you you have jQuery loaded and use jQuery syntax in your code.