Skip to main content

URL Input Validation

Overviewโ€‹

When registering Builder components with URL/link inputs, use type: 'text' with the urlInputValidation helper instead of type: 'url'.

Why Do We Not Use type: 'url'?โ€‹

Builder's native url input type has 2 main limitations:

  1. Inconsistent validation - Native URL validation doesn't allow certain url param combinations that we need. For example: /collections/bridesmaid-dresses?filter.tags_fabric=luxe+knit is not valid using Builder's url input as the space encoded character is recognized as invalid
  2. No custom regex validation support - Since we need to use regex to validate url structures in #1, Builder's regex validation option only works with type: 'text', not type: 'url' or type: 'string'

The urlInputValidation Helperโ€‹

Import from ~/lib/builder/helper:

import { urlInputValidation } from '~/lib/builder/helper';

Usageโ€‹

// Before
{
name: 'url',
type: 'url',
required: true,
}

// After
{
name: 'url',
type: 'text',
required: true,
...urlInputValidation,
}

What It Validatesโ€‹

The helper uses regex validation that accepts:

PatternExampleValid
Absolute URLs (HTTPS)https://birdygrey.com/bridesmaid-dressesYes
Absolute URLs (HTTP)http://example.comYes
Relative paths/collections/bridesmaid-dressesYes
Path with encoded characters/collections/bridesmaid-dressesYes
Anchors#section-nameYes
Query parameters/search?q=dressYes
Paths with anchors/page#sectionYes

The helper rejects:

PatternExampleValid
Plain textclick hereNo
Whitespacehttps://example.com /pathNo
mailto linksmailto:email@example.comNo
tel linkstel:+1234567890No

Validation Messageโ€‹

When validation fails, editors see:

Must be a valid URL (https://...), relative path (/...), or anchor (#...). Double check no white spaces are included.

Full Exampleโ€‹

import type { RegisteredComponent } from '@builder.io/sdk-react';
import MyComponent from '~/components/MyComponent';
import { urlInputValidation } from '~/lib/builder/helper';

export default {
component: MyComponent,
name: 'My Component',
inputs: [
{
name: 'title',
type: 'string',
required: true,
},
{
name: 'ctaUrl',
friendlyName: 'CTA URL',
type: 'text', // Must be 'text', not 'url' or 'string'
required: true,
...urlInputValidation,
},
],
} satisfies RegisteredComponent;

Migration Notesโ€‹

If Builder's url input type changes to satisfy all the url structures we need, we can then deprecate this helper and switch all component's input types of text (that are meant for urls) back over to the url input type.