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:
- Inconsistent validation - Native URL validation doesn't allow certain url param combinations that we need. For example:
/collections/bridesmaid-dresses?filter.tags_fabric=luxe+knitis not valid using Builder's url input as the space encoded character is recognized as invalid - No custom regex validation support - Since we need to use regex to validate url structures in #1, Builder's
regexvalidation option only works withtype: 'text', nottype: 'url'ortype: '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:
| Pattern | Example | Valid |
|---|---|---|
| Absolute URLs (HTTPS) | https://birdygrey.com/bridesmaid-dresses | Yes |
| Absolute URLs (HTTP) | http://example.com | Yes |
| Relative paths | /collections/bridesmaid-dresses | Yes |
| Path with encoded characters | /collections/bridesmaid-dresses | Yes |
| Anchors | #section-name | Yes |
| Query parameters | /search?q=dress | Yes |
| Paths with anchors | /page#section | Yes |
The helper rejects:
| Pattern | Example | Valid |
|---|---|---|
| Plain text | click here | No |
| Whitespace | https://example.com /path | No |
| mailto links | mailto:email@example.com | No |
| tel links | tel:+1234567890 | No |
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.