PrimitivesLast updated on
Last updated on
Build and validate primitive data types
Primitives are structured data types used throughout OpenForm for representing common values like money, addresses, coordinates, and more. Each primitive has:
- Object pattern: Pass a plain object for validation
- Builder pattern: Chain methods for incremental construction
- Static methods:
parse()andsafeParse()for validation
Available Primitives
| Primitive | Description |
|---|---|
| address | Postal address |
| bbox | Bounding box |
| coordinate | Lat/lng point |
| date | Date (YYYY-MM-DD) |
| datetime | Date and time |
| duration | ISO 8601 duration |
| identification | ID document |
| money | Monetary amount with currency |
| organization | Organization info |
| percentage | Percentage value |
| person | Person name |
| phone | Phone number (E.164) |
| rating | Rating value |
| time | Time only |
Usage Patterns
Object Pattern
Pass a plain object for immediate validation:
import { money } from '@open-form/core'
// Validates and returns the Money object
const price = money({ amount: 99.99, currency: 'USD' })
// Throws if invalid
const invalid = money({ amount: 'not a number', currency: 'USD' })
// Error: Invalid Money: amount must be a numberBuilder Pattern
Chain methods to construct incrementally:
import { money } from '@open-form/core'
const price = money()
.amount(99.99)
.currency('USD')
.build()Static Methods
Parse unknown data from external sources:
import { money } from '@open-form/core'
// Throws on error
const price = money.parse(jsonData)
// Returns result object
const result = money.safeParse(jsonData)
if (result.success) {
console.log(result.data.amount)
} else {
console.error(result.error)
}Using with Forms
Primitives are commonly used when filling form data:
import { open, money, address } from '@open-form/core'
const form = open.form({
name: 'invoice',
fields: {
total: { type: 'money', label: 'Total Amount' },
billingAddress: { type: 'address', label: 'Billing Address' }
}
})
const filled = form.fill({
fields: {
total: money({ amount: 150.00, currency: 'USD' }),
billingAddress: address()
.line1('123 Main Street')
.locality('New York')
.region('NY')
.postalCode('10001')
.country('US')
.build()
}
})Related
- Form Fields - Field types that use primitives
- Primitive Schemas - JSON Schema definitions