APIs & Integrations

CVlad
Membre

Custom validation & prevent form submision

Résolue

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.

1 Solution acceptée
SteveHTM
Solution
Conseiller clé | Partenaire solutions
Conseiller clé | Partenaire solutions

Custom validation & prevent form submision

Résolue

There are some great ideas on form functionality extensions here and elsewhere in the community. I've found this incredibly helpful, but its sometime hard to hunt for. 

 

Is there any chance that someone could formally update the foundationn document for form extensions at https://legacydocs.hubspot.com/docs/methods/forms/advanced_form_options with some of the more complete and innovative functionality thats been discussed here?

 

Steve

Steve Christian

HTM Solutions

https://info.htmsolutions.biz/meetings/stevec2

mobilePhone
+1 6195183009
emailAddress
stevec@htmsolutions.biz
website
www.htmsolutions.biz
address
San Diego, CA
Create Your Own Free Signature

Voir la solution dans l'envoi d'origine

0 Votes
5 Réponses
kgeddon
Membre

Custom validation & prevent form submision

Résolue

Custom validation is a great way to ensure data integrity before a form submission. I have implemented custom validation in JavaScript to check for specific conditions like input length or format, and prevent submission if they are not met. It is always important to give clear error messages to guide the user. Anyone else have tips for handling more complex validation scenarios?

 
0 Votes
DavidClark08
Contributeur

Custom validation & prevent form submision

Résolue

Thank you so much for sharing! 

 

I've seen  your post so it's included under "Top Community Conversations"on homepage

.

0 Votes
SteveHTM
Solution
Conseiller clé | Partenaire solutions
Conseiller clé | Partenaire solutions

Custom validation & prevent form submision

Résolue

There are some great ideas on form functionality extensions here and elsewhere in the community. I've found this incredibly helpful, but its sometime hard to hunt for. 

 

Is there any chance that someone could formally update the foundationn document for form extensions at https://legacydocs.hubspot.com/docs/methods/forms/advanced_form_options with some of the more complete and innovative functionality thats been discussed here?

 

Steve

Steve Christian

HTM Solutions

https://info.htmsolutions.biz/meetings/stevec2

mobilePhone
+1 6195183009
emailAddress
stevec@htmsolutions.biz
website
www.htmsolutions.biz
address
San Diego, CA
Create Your Own Free Signature
0 Votes
matt_scott
Contributeur de premier rang | Partenaire solutions Platinum
Contributeur de premier rang | Partenaire solutions Platinum

Custom validation & prevent form submision

Résolue

Thanks this looks great

Previously I've set the validation on the click event on the button in the onFormReady

Although it's a 'click' event apparently the click is triggered when someone hits enter too

e.g. in quick jQuery

$(submitButton).on('click',function(e){
  if(do some custom validation) {
    e.preventDefault();
  }
}

 That code needs to be in the onFormReady and you obviously need to use the correct selectors

Matthew Scott
Head of Development | Hubspot Solutions Architect

B2B marketing agency: Specialist B2B content marketing and demand generation for SaaS vendors and HubSpot Users | Deeply Digital | HubSpot Partner since 2010


01926 334003

deeplydigital.co.uk

3 Morton Street, Leamington Spa, CV32 5SY, UK
0 Votes
MiaSrebrnjak
Gestionnaire de communauté
Gestionnaire de communauté

Custom validation & prevent form submision

Résolue

Hi @CVlad

 

Thank you so much for sharing! 💛

I've highlighted your post so it's included under "Top Community Conversations" on our homepage. 🙂 

 

Cheers
Mia, Community Team


Join us on March 27th at 12 PM for the Digital Essentials Lab, an interactive session designed to redefine your digital strategy!
Engage with expert Jourdan Guyton to gain actionable insights, participate in live Q&A, and learn strategies to boost your business success.
Don't miss this opportunity to connect and grow—reserve your spot today!


Besuche unsere DACH-Community!
Nimm an regionalen Unterhaltungen teil, indem du deine Spracheinstellungen änderst !


Our Community is available in other languages.
Join regional conversations by changing your language settings !

0 Votes