Blog

HubSpot Forms API: Handling Validation Errors

By
The Reform Team
Use AI to summarize text or ask questions

Handle HubSpot Forms API errors by checking the HTTP status and response body, then deciding whether to correct input, fix the integration, or retry. Keep entered values intact, and never treat a timeout as proof that a submission failed.

The recovery path depends on the error:

  • Invalid input: Match errors such as INVALID_EMAIL to the right fields and show accessible messages beside them.
  • Form or access problems: Stop retries and alert the integration owner.
  • Rate limits or server failures: Follow retry guidance and use limited retries with increasing delays.
  • Timeouts: Mark the outcome as unknown and check submission status, where possible, before resending.

Check form IDs, required fields, and internal property names before submitting. Then test each recovery path, log diagnostic details without submitted values, and track validation failures separately from temporary failures.

HubSpot Forms API Error-Handling Flow

HubSpot Forms API Error-Handling Flow

Submit Data and Read Error Responses

Read the HTTP Status and Response Body

Once the request matches HubSpot’s form definition, check the HTTP status first, then parse the body. You can identify a validation error only after HubSpot responds. A network exception means you don’t know whether HubSpot received the request.

async function readSubmissionResult(requestSubmission) {
  let response;

  try {
    response = await requestSubmission();
  } catch {
    return { kind: "unknown" };
  }

  let body = null;
  try {
    const text = await response.text();
    if (text) body = JSON.parse(text);
  } catch {
    // Empty, unreadable, or non-JSON response.
  }

  return {
    kind: response.ok ? "success" : "http-error",
    status: response.status,
    body,
    correlationId:
      typeof body?.correlationId === "string" ? body.correlationId : undefined
  };
}

Treat an empty or non-JSON body as a response parsing issue - not a field validation error.

Convert Error Details to a Common Format

After parsing the response, convert errors to a common format before passing them to the UI. HubSpot returns structured errors, but property names can vary. Don’t guess field names from message text.

normalize(body, correlationId):
  details = body.errors if it is a nonempty array else [{}]

  return details.map(detail => {
    code = stringOrUndefined(detail.errorType)

    category =
      code == "MISSING_SCOPE" ? "auth" :
      code == "TOO_MANY_REQUESTS" ? "rate-limit" :
      code == "SERVER_ERROR" ? "server" :
      code == "FORM_NOT_PUBLISHED" ||
      code == "FORM_NEVER_EXISTED" ||
      code == "OUT_OF_DATE" ? "form" :
      "request"

    return {
      field: stringOrUndefined(detail.context?.in),
      message: stringOrUndefined(detail.message) ?? stringOrUndefined(body.message),
      category: category,
      code: code,
      correlationId: correlationId
    }
  })

Use the error code when it’s present. If an error doesn’t map clearly to a field, leave field blank instead of marking every input invalid.

Show Form-Level Messages for Unmapped Errors

If no field matches the error, show a safe form-level message above the form - not beside an input. Keep the user’s entered values so they can retry without starting over, a key benefit of multi-step forms.

Show Field Errors Without Losing Input

After normalizing an error, map it to the affected fields and place each message beside the right control.

Map HubSpot property names to visible input IDs: email → work-email, company → company-name. Handle REQUIRED_FIELD as missing input, INVALID_EMAIL as a format error, VALUE_NOT_IN_FIELD_DEFINITION as an unsupported choice, and INPUT_TOO_LARGE as a value over the limit. FIELD_NOT_IN_FORM_DEFINITION is an integration bug, not a visitor error.

Set aria-invalid="true" on affected inputs. Use aria-describedby to connect each input to its visible error message while keeping links to existing help text. Place a linked error summary above the form.

After submission, move focus to the summary if several fields fail, or to the invalid field if only one needs attention. Announce the summary through a live region, but don't make that the only cue. Never display credentials, stack traces, or raw HubSpot responses.

Keep Entered Values After a Failure

Preserve text, selections, and consent choices across failed submissions using client state or a protected server session. Define retention rules for sensitive fields, and repopulate them only if your security model allows it.

Tie each response to the current attempt and field values so an older response can't overwrite newer edits. Clear a field error once local validation passes. For server-only rules, clear it only after a successful resubmission. Keep unrelated errors visible.

Hypothetical SaaS demo-request form: Keep Company: Acme Analytics and Work email: alex@acmeanalytics.com in place while the visitor changes an unsupported company-size value to 51–200 employees. Show “Select a supported company size.” beside that control, with a summary linking to the one field needing attention.

If the visitor can't fix the error, treat it as a retry decision - not a field message.

Decide When to Correct or Retry

Once you've classified the error, decide whether the visitor can fix it now or needs to retry later.

Disable repeated clicks while a request is in flight. Track each attempt's ID, retry count, and outcome. For temporary failures, follow any supplied retry guidance and use bounded exponential backoff. Don't automatically retry generic client errors.

A timeout or some server failures can leave the outcome unknown. Locking the form on the client doesn't guarantee server-side deduplication.

Failure class User-facing message Application action
Invalid data or malformed request “Correct the highlighted fields and try again.” Show field-level messages; do not automatically retry.
Authentication or configuration failure “This form is unavailable. Please try again later.” Stop retries, log safely, and alert the integration owner.
Rate limit “Too many requests. Please wait before trying again.” Honor retry guidance, apply bounded backoff, and disable repeated clicks.
Temporary server failure “The service is temporarily unavailable. Please try again.” Retry only a limited number of times with backoff, then offer manual retry.
Network timeout “The submission outcome is unknown. Check your connection before trying again.” Preserve input, mark the attempt as uncertain, and offer a deliberate manual retry.

Log Errors and Test Recovery

Once you know whether a failure can be fixed or retried, log it and test the recovery path.

Log Diagnostic Details Safely

After classifying a failure, log enough detail to debug it without exposing user data. Record the form ID, attempt ID, HTTP status, normalized category and code, affected field, HubSpot correlation ID, and retry count. Keep the correlation ID available for support investigations.

Use ISO 8601 timestamps with a time zone. Reserve U.S.-formatted dates for user-facing reports.

Limit logs to field names and other non-sensitive metadata. Never log credentials, PII, payment data, or submitted values. Restrict log access and choose a retention period that fits your troubleshooting needs.

Use the same error categories in test cases and production logs.

Test Validation Errors and Request Failures

Before deployment, test documented validation, configuration, and authentication failures. Mock rate limits, timeouts, server errors, and empty or non-JSON responses. Each case should produce a usable message - not a parsing error or a silent failure.

Test the entire correction path, from the error to a successful submission. Check message placement, accessible focus, and recovery. Include timeout cases in the same recovery test suite, and verify that logs exclude sensitive data.

Once recovery works, measure how often each failure class occurs.

Track Submission Failure Rates

Compare failed attempts with total attempts by form, affected field, and the same normalized failure classes used in the UI and logs. Keep invalid-data failures separate from temporary request failures. Track retries separately so they don’t distort the initial-submission failure rate.

Alert the integration owner to configuration errors or sustained temporary failures. Include only diagnostic metadata in those alerts.

For Reform, include email validation and HubSpot monitoring in recovery tests. Front-end validation does not replace API error handling.

Conclusion: Error-Handling Checklist

Review the final submission path using the error classification from earlier sections. Read the HTTP status and response body, classify the error, and display only messages meant for users.

  • Clear feedback: Link field errors to their inputs. For errors that don’t map to a field, show an accessible form-level message.
  • Preserved input: Keep entered values so users can correct them.
  • Correct recovery: Require users to correct invalid data. Retry temporary failures with bounded backoff, but stop on authentication or configuration errors.
  • Timeout safeguards: Treat timeouts as uncertain outcomes. Confirm whether the submission succeeded before resending.
  • Deployment readiness: Verify that recovery paths have been tested, diagnostic logs are safe, and monitoring distinguishes validation failures from temporary failures.

FAQs

How can I check whether a timed-out submission succeeded?

Treat a timeout as an uncertain delivery status. A successful HTTP response means HubSpot received the request. It does not confirm that the CRM update finished or the record was created.

Before retrying, search HubSpot for the lead by email address or unique identifier. Also check the form submission history or use the retrieval endpoint to confirm whether the record exists.

How should I handle multiple errors for one field?

Focus on the error that needs attention first. Parse the array of issues in the response body, then turn errors like missing required values or incorrect formats into clear instructions for fixing the input.

Show each message next to its field in red text with a warning icon. Keep all previously entered data while the user makes corrections.

How can I preserve form input without storing sensitive data?

Keep user input in temporary local storage or application state until submission succeeds, then clear it. After validation errors, keep raw personally identifiable information (PII) and full payloads out of backend logs.

Log only non-sensitive metadata: timestamps, error codes, correlation IDs, and sanitized field summaries. If debugging requires keeping data, hash or tokenize PII, encrypt the stored evidence, and use a short retention period.

Related Blog Posts

Use AI to summarize text or ask questions

Discover proven form optimizations that drive real results for B2B, Lead/Demand Generation, and SaaS companies.

Lead Conversion Playbook

Get new content delivered straight to your inbox

By clicking Sign Up you're confirming that you agree with our Terms and Conditions.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
The Playbook

Drive real results with form optimizations

Tested across hundreds of experiments, our strategies deliver a 215% lift in qualified leads for B2B and SaaS companies.