OpenForm

Primitives

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() and safeParse() for validation

Available Primitives

PrimitiveDescription
addressPostal address
bboxBounding box
coordinateLat/lng point
dateDate (YYYY-MM-DD)
datetimeDate and time
durationISO 8601 duration
identificationID document
moneyMonetary amount with currency
organizationOrganization info
percentagePercentage value
personPerson name
phonePhone number (E.164)
ratingRating value
timeTime 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 number

Builder 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

On this page