Required fields after form been loaded using JS

Hello everyone,

I’m creating a page with a Hubspot form. This form contains hidden fields that, depending on some parameters in the URL, these fields become visible, through JS code in a custom module that I’m also developing.

The problem I’m having is that when these fields become visible, they need to become required as well. But I’m not able to do this through Javascript.

I tried using JQUERY’s “$(‘input’).prop(‘required’, true)” function. The attribute is inserted in the tag, but the validation of these fields does not work when submitting the form.

Is there any way using JS, to make them required after the form has been loaded into the page, by Hubspot standards? Or do I need to take another kind of approach?

Can anybody help me?

Thanks,

Do not think that setting the required tag will work.
Hacky solution I came up with:
Make them required by default in HubSpot and set a default value through JavaScript or jQuery (something like “empty” or “null”). Once the requirements are met to show that field, show them and empty the value. That way the user has to set a value.
Downside is that if the fields are not shown to a user, the “empty” or “null” value will be set as a property value. You should be able to empty those with a workflow tho.
Like I said, hacky solution, but might work.

Alternative would be to customize the form embed code (https://legacydocs.hubspot.com/docs/methods/forms/advanced_form_options) and use the onFormSubmit callback to do some extra validation on the hidden fields. Not sure if you can prevent the form from submitting, but could be worth a shot.

Hi @Teun,

Thanks for the reply! I forgot to mention that these fields are file type fields and that complicates things a bit more. Because I don’t think I can set a default value for them.

But I believe that custom form embedding code would be the solution. Perhaps creating a custom validation on these fields in the form submission callback might work. I still don’t know how to do this, but I’ll look into the best way to do it.

Thanks for your help!

Cheers,

Hi!
Just read some more posts regarding this issue and you need the onFormReady callback instead cause you can not prevent the form from submitting.
Here are two suggestions that might help:
https://rschu.me/prevent-the-submit-of-any-hubspot-forms-after-a-successful-validation-5e1f230b14f1
https://community.hubspot.com/t5/APIs-Integrations/Prevent-Form-submission-after-successful-Validation/td-p/317171

Hello @Teun,

Thanks again for the reply!

I’ve also read some things about this, that the onFormSubmit callback doesn’t prevent form submission. I’m going to try using the onFormReady callback to see if I get the results I need.

Anyway, thanks so much for the help!

Cheers,