Use HubSpot forms to capture information from website visitors, which you can then access throughout HubSpot. You can share links to forms directly with users, submit form data via the API, and embed them on your website pages using the CMS. Below, find reference documentation for forms, including form embed configuration options, internationalization and validation error messages, and form events.
If you're using jQuery to manipulate the values of form inputs (i.e. using val()
or prop()
), you must trigger a change event using change()
or trigger('change')
for the change to properly register.
Examples:
$('input[value="checkbox_1"]').prop('checked', true).change();
$('input[name="firstname"]').val('Brian').change();
If not using jQuery:
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
For Checkboxes:
input.click()
When embedding a form, you can include the following customization options in the form embed code.
Please note:
- Form customization options are only available for forms created in HubSpot that have been set as raw HTML. The HubSpot account must have a Marketing Hub or Content Hub Professional or Enterprise subscription.
- HubSpot forms should only be loaded using the HubSpot-hosted JavaScript file. Making a copy of the form embed code and self-hosting it is not supported. Any improvements that HubSpot makes to improve security, anti-spam, accessibility, and performance will not propagate to your form if you decide to self-host the HubSpot form embed code.
xxxxxxxxxx
<script
charset="utf-8"
type="text/javascript"
src="//js.hsforms.net/forms/embed/v2.js"
></script>
<script>
hbspt.forms.create({
region: 'na1',
portalId: '123456',
formId: 'df93f0c1-2919-44ef-9446-6a29f9a7f',
});
</script>
Parameter | Type | Description |
---|---|---|
portalId Required | Number or string | The ID of the HubSpot account that the form was created in. This is used to retrieve the form definition. |
formId Required | String | The form's ID, which is used to retrieve the form definition. |
region | String | The region of the account where the form was created. This is used to retrieve the form definition. Possible values are na1 or eu1 . |
target | String | A valid CSS selector string, specifying an existing element on the page into which the form will be embedded.If you're including multiple forms on the page, it is strongly recommended that you include a separate, specific target for each form. It's strongly recommended you specify this property, otherwise the form is injected after the script location. |
redirectUrl | String | The URL that the form will redirect to upon successful submission. Cannot be used with inlineMessage . |
inlineMessage | String | The message to display in place of the form upon successful submission. Cannot be used with redirectUrl . |
pageId | Number or string | The ID of the HubSpot page that you're embedding the form on. Associates the form submissions with the page. |
cssRequired | String | CSS string specific to validation error messages and form styling. Set this property to an empty string if you don't want to apply default HubSpot styling to the form elements. |
cssClass | String | The class that will be applied to the form. |
css | String | A CSS string that, when defined, is used instead of the built-in CSS theme. This can be used for setting your own CSS styling. |
submitText | String | String that overrides the submit button text. |
submitButtonClass | String | CSS class that will be applied to the submit button instead of the default .hs-button.primary.large . |
errorClass | String | CSS class that will be applied to the inputs with validation errors instead of the default .invalid.error . |
errorMessageClass | String | CSS class that will be applied to error messages instead of the default .hs-error-msgs.inputs-list . |
locale | String | The form's locale, which is used to customize language for form errors, date pickers, labels, and links. Learn more about adding internationalized error messages. |
translations | Object | An object containing additional translation languages or to override field labels and messages for existing languages. Learn more about adding internationalization. |
manuallyBlockedEmailDomain | Array | Array of domains, specified as strings, to block in email input fields. |
formInstanceId | String | Required when embedding the same form on the same page multiple times. This ID can be arbitrary, so long as it's unique. |
The form embed code includes event callbacks that you can use to extend form functionality when the events below occur. These are separate from the global form events that you can hook into.
xxxxxxxxxx
<script
charset="utf-8"
type="text/javascript"
src="//js.hsforms.net/forms/embed/v2.js"
></script>
<script>
hbspt.forms.create({
portalId: '',
formId: '',
onBeforeFormSubmit: function ($form) {
// YOUR SCRIPT HERE
},
});
</script>
Parameter | Type | Description |
---|---|---|
onBeforeFormInit | Function | A callback that executes before the form builds. Takes form configuration object as a single argument: onBeforeFormInit(ctx) . |
onFormReady | Function | A callback that executes just before the form render. This callback should be used for any logic that needs to execute when the form has fully rendered on the page. Takes the jQuery form object as the argument: onFormReady($form) . |
onFormSubmit | Function | A callback that executes after the form is validated and before the form is submitted (i.e., right before the data is actually sent). This is for any logic that needs to execute before submission is initiated. Any changes made to form fields will not be validated. Takes the jQuery form object as the argument: onFormSubmit($form) .It is not recommended to perform a browser redirect in this callback, as it could prevent the form submission. For any custom redirects, use the onFormSubmitted callback. |
onBeforeFormSubmit | Function | A callback that executes after the form is validated, before the form is submitted i.e. before the data is actually sent. This is for any logic that needs to execute before submission is initiated. Any changes made to fields will not be validated. This callback behaves in the same way as onFormSubmit , but is preferred due to the accurate naming of when it is triggered. Takes the jQuery form object as the argument and an array of submission values: onBeforeFormSubmit($form, submissionValues) . As in the case of onFormSubmit , It is not recommended to perform a browser redirect in this callback as this could prevent before the submission is initiated, thus preventing form submissions. For any custom redirects, please use the onFormSubmitted callback. |
onFormSubmitted | Function | Callback that executes after form submission. This is for executing actions when the submission is fully complete, such as displaying a confirmation or thank you message, or performing a custom redirect. Takes the jQuery form object as the argument and an array of submission values: onFormSubmitted($form, data) .The callback's arguments are the form element and an object containing two properties:
|
By default, HubSpot provides a set of translated date picker field labels and validation messages for a set of supported languages. You can also add custom languages or override specific error messages and date picker months/days displayed on the form using the translation parameter.
To include the default translated strings for a supported language, add the locale
parameter to the embed code, followed by one of the languages in the table below.
xxxxxxxxxx
hbspt.forms.create({
portalId: '',
formId: '',
locale: 'fi',
});
Value | Language |
---|---|
en | English |
da | Danish |
de | German |
es | Spanish (Spain) |
es-mx | Spanish (Mexico) |
fi | Finnish |
fr | French |
it | Italian |
ja | Japanese |
nl | Dutch |
pl | Polish |
pt-br | Portuguese (Brazil) |
sv | Swedish |
zh-cn | Chinese |
zh-hk | Chinese (Hong Kong) |
To add custom languages or override field labels and default translated strings, you can pass language objects into the translations
parameter that correspond to the desired locale
.
For supported locales, you only need to provide the keys and messages you wish to override. For example, the code below configures the form to replace the email
field label, required field validation message, and submit button text with custom strings.
Learn more about validation below.
xxxxxxxxxx
hbspt.forms.create({
portalId: '',
formId: '',
locale: 'en',
translations: {
en: {
fieldLabels: {
email: 'Electronic mail',
},
required: "Hey! That's required!",
submitText: 'Custom Submit Button Text',
},
},
});
Value | Type | Language |
---|---|---|
translations | Object | An object containing additional translation languages or to override field labels and messages for existing languages. |
en | Object | An object containing custom translations for the specified locale . |
fieldLabels | Object | An object containing field label replacement values. In this object, you'll specify the name of the form field followed by your custom label. |
required | String | Replaces the validation message for required field errors with a custom message. |
submitText | String | Replaces the submit button text with a custom string. |
In addition to the supported locales, you can register new locale codes in the locale
parameter. In this case, make sure to specify messages for all of the keys listed in the table below. Omitted keys will show a "missing translation" message in their place.
Key | English default |
---|---|
learnMore | Learn more |
submitText | Submit |
previousMonth | Previous Month |
nextMonth | Next Month |
january | January |
february | February |
march | March |
april | April |
may | May |
june | June |
july | July |
august | August |
september | September |
october | October |
november | November |
december | December |
sunday | Sunday |
monday | Monday |
tuesday | Tuesday |
wednesday | Wednesday |
thursday | Thursday |
friday | Friday |
saturday | Saturday |
sundayShort | Sun |
mondayShort | Mon |
tuesdayShort | Tue |
wednesdayShort | Wed |
thursdayShort | Thu |
fridayShort | Fri |
saturdayShort | Sat |
fallbackDescription | We had some trouble loading this form. |
fallbackCta | Click here to continue. |
fallbackGenericDescription | This form didn't load. Please try again later. |
fileTooLarge | Selected file is too large. Maximum allowed size is 100MB. |
defaultSelectOptionLabel | Please Select |
notYou | Not you? |
resetTheForm | Click here to reset. |
HubSpot provides three layers of form validation:
- Live validation: validation that occurs while a visitor is filling out a form.
- Client-side validation: validation that occurs after the visitor attempts to submit the form, but before the submission request has been sent to the server.
- Server-side validation: validation that occurs after form submission.
During each step of validation, HubSpot provides a set of default error messages. These messages can be overridden by using the locale
and translation
parameters in the form embed code. Below, learn more about the default validation error messages and how to override them depending on when they occur.
Below are the currently supported live validation field error keys for contextual overriding. These error keys can be specified in the language object of the translations
parameter.
xxxxxxxxxx
hbspt.forms.create({
portalId: '',
formId: '',
locale: 'en',
translations: {
en: {
required: "Hey! That's required!",
invalidEmailFormat: 'Email address formatted incorrectly.',
invalidNumber: 'Not a valid number.',
},
},
});
Error key | English default |
---|---|
requiredField | Please complete this required field. |
required | Please complete this required field. |
missingSelect | Please complete this required field. |
missingOptionSelection | Please complete this required field. |
fileTooLarge | Selected file is too large. Maximum allowed size is 100MB. |
invalidEmailFormat | Email must be formatted correctly. |
phoneInvalidCharacters | A valid phone number may only contain numbers and any of the following characters: + , ( , ) , - , x . |
invalidNumber | Please enter a valid number. |
invalidDate | Please enter a valid date. |
invalidEmail | Please enter a valid email address. |
invalidNumberRangeTooSmall | Please enter a number that's greater than or equal to . |
invalidNumberRangeTooLarge | Please enter a number that's less than or equal to . |
forbiddenEmailDomain | Please enter a different email address. This form does not accept addresses from {domain} . |
manuallyBlockedEmailDomain | Please enter a different email address. This form does not accept addresses from {domain} . |
numberOutOfRange | The number you entered is not in range. |
inputTooLarge | Please use fewer than 65536 characters. |
The following errors may be generated and displayed client-side. They can be contextually overridden using a submissionErrors
object.
xxxxxxxxxx
hbspt.forms.create({
portalId: '',
formId: '',
locale: 'en',
translations: {
en: {
submissionErrors: {
MISSING_REQUIRED_FIELDS: 'Please fill in all required fields.',
},
},
},
});
Error key | English default |
---|---|
submissionErrors.MISSING_REQUIRED_FIELDS | Please complete all required fields. |
submissionErrors.BLOCKED_EMAIL | Please change your email address to continue. |
submissionErrors.TOO_MANY_REQUESTS | There was an issue submitting your form. Please wait a few seconds and try again. |
The following errors may be generated on the server after a submission request has been sent and displayed client-side when a response is received. They can be contextually overridden using a submissionErrors
object.
xxxxxxxxxx
hbspt.forms.create({
portalId: '',
formId: '',
locale: 'en',
translations: {
en: {
submissionErrors: {
SERVER_ERROR: 'Sorry, something went wrong. Please try again.',
},
},
},
});
Error key | English default |
---|---|
submissionErrors.SERVER_ERROR | Sorry, something went wrong and the form was not submitted. Please try again later. |
submissionErrors.RECAPTCHA_VALIDATION_ERROR | Failed to validate Captcha. Please try again. |
submissionErrors.OUT_OF_DATE | This form is no longer current. Please refresh the page and try again. |
submissionErrors.FORM_NOT_PUBLISHED | This form is no longer active. Please refresh the page and try again. |
submissionErrors.MISSING_SCOPE | This form cannot be submitted. Please contact the site owner. |
submissionErrors.FORM_NEVER_EXISTED | This form cannot be submitted. Please contact the site owner. |
submissionErrors.FORM_TYPE_MISMATCH | This form cannot be submitted. Please contact the site owner. |
submissionErrors.FILE_TOO_LARGE | Selected file is too large. Maximum allowed size is 100MB. |
Forms allow two ways to bind functionality onto events, including callbacks in the HubSpot form embed code and global form events.
Use these events to trigger custom JavaScript. If you need complete control over the styles and actions of your form, it's recommended that you build your own custom form and submit the data using the Forms API.
xxxxxxxxxx
// Example event listener:
window.addEventListener('message', (event) => {
if (
event.data.type === 'hsFormCallback' &&
event.data.eventName === 'onFormSubmitted'
) {
someAnalyticsLib('formSubmitted');
console.log('Form Submitted! Event data: ${event.data}');
}
});
Please note:
- These events are non-blocking, so it's not possible to prevent a form submission using the
onFormSubmit
callback. - You cannot change form submission data using
onBeforeFormSubmit
. When usingonBeforeFormSubmit
, the form is submitted as the event is emitted to the browser. Any listeners hooked to the events do not block the main thread of the form's execution. For synchronous changes to the form, it is recommended to customize the form embed code instead.
Called before the form has been inserted into DOM.
xxxxxxxxxx
// onBeforeFormInit event arguments
{
type: 'hsFormCallback',
eventName: 'onBeforeFormInit',
id: 'Id of form submitted',
data: {}
}
Called after the form has been inserted into DOM.
xxxxxxxxxx
// onFormReady event arguments
{
type: 'hsFormCallback',
eventName: 'onFormReady',
id: 'Id of form submitted',
data: {}
}
Called at the start of form submission, but before submission has been persisted. Behaves the same as onFormSubmit
, but is preferred due to more accurate naming indicating when this event is triggered.
When performing custom redirects, use onFormSubmitted instead, as this event may prevent submissions being initiated, thus preventing form submissions.
xxxxxxxxxx
// onBeforeFormSubmit event arguments
{
type: 'hsFormCallback',
eventName: 'onBeforeFormSubmit',
id: 'ID of the form to submit',
data: [
// Array containing the names and values
// of the fields about to be submitted
{
name: 'email',
value: 'test@example.com'
},
{
name: 'firstName',
value: 'Jane'
},
{
name: 'lastName',
value: 'Doe'
}
]
}
Called at the start of form submission, but before submission has been persisted. Please use onBeforeFormSubmit
instead.
When performing custom redirects, use onFormSubmitted instead, as this event may prevent submissions being initiated, thus preventing form submissions.
xxxxxxxxxx
// onFormSubmit event arguments
{
type: 'hsFormCallback',
eventName: 'onFormSubmit',
id: 'ID of the form to submit',
data: [
// Array containing the names and values
// of the fields about to be submitted
{
name: 'email',
value: 'test@example.com'
},
{
name: 'firstName',
value: 'Jane'
},
{
name: 'lastName',
value: 'Doe'
}
]
}
Called after the form has been submitted and the submission has persisted. Recommended for performing custom redirects.
xxxxxxxxxx
// onFormSubmitted event arguments
{
type: 'hsFormCallback',
eventName: 'onFormSubmitted',
id: 'ID of form submitted',
data: {
// String containing redirect url, if set
redirectUrl: "https://example-url.com",
// Object containing key-value pairs of submitted data
submissionValues: {
'email': 'test@example.com',
'firstName': 'Jane',
'lastName': 'Doe'
}
}
}