Hello all,
Just found a solution for doing a basic validation on fields before submit on a hubspot form.
Conditions:
Raw html form
Include jquery
Code
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/embed/v2.js"></script>
<script>
hbspt.forms.create({
region: "...",
portalId: "123123",
formId: "xxxxxxx",
onFormReady: function () {
// Use a more specific selector if possible
var formSelector = '#hsForm_xxxxxx'; // Replace with your form's specific class or ID
var form = document.querySelector(formSelector);
if (form) {
var firstnameField = form.querySelector('[name="firstname"]');
var submitButton = form.querySelector('input[type="submit"], button[type="submit"]');
if (firstnameField && submitButton) {
// Initially disable the submit button
submitButton.disabled = true;
firstnameField.addEventListener('input', function() {
var value = firstnameField.value;
if (isValid(value)) {
clearError();
submitButton.disabled = false;
} else {
showError('The field format is invalid. It should be 2 letters followed by 8 numbers.');
submitButton.disabled = true;
}
});
} else {
console.error('Form elements not found');
}
} else {
console.error('Form not found');
}
function isValid(value) {
var regex = /^[A-Za-z]{2}\d{8}$/; // This matches XX12345678
return regex.test(value);
}
function showError(message) {
console.error(message); // Placeholder implementation
// Add UI logic here to display the message
}
function clearError() {
// Add UI logic here to clear the displayed error message
}
}
});
</script>
This code will disable the submit button until the field matches the regex.
You can add as many form validations you like and also add error message until the fields matches the regex.
Hope this helps.