@tgb-form/core
v0.0.4
Published
An easy to use form library, with powerful schema-based form definition capabilities.
Readme
@tgb-form/core
Portable form definitions for TanStack Form and Valibot.
@tgb-form/core owns the data layer: JSON-safe schemas, validation rules, serialization, renderer keys, custom validator references, and TanStack-compatible options. Framework packages render those definitions. It stays close to TanStack Form and Valibot instead of wrapping them in a second abstraction layer.
Quick Start
import {
defineForm,
deserializeForm,
FieldDataType,
type InferFormValues,
serializeForm,
toTanStackOptions,
toValibotSchema,
ValidationRuleKind,
} from '@tgb-form/core';
const form = defineForm({
fields: {
email: {
type: FieldDataType.String,
defaultValue: '',
label: 'Email',
component: 'email-input',
props: { autocomplete: 'email' },
rules: [
{ kind: ValidationRuleKind.Required, message: 'Email is required' },
{ kind: ValidationRuleKind.Email, message: 'Enter a valid email' },
],
},
subscribed: {
type: FieldDataType.Boolean,
defaultValue: true,
label: 'Subscribe',
},
},
});
const stored = JSON.stringify(serializeForm(form));
const restored = deserializeForm(stored);
const schema = toValibotSchema(restored);
const tanstackOptions = toTanStackOptions(restored);
type FormValues = InferFormValues<typeof form>;
// { email: string; subscribed: boolean }InferFormValues is the canonical way to derive the value shape of a code-authored
definition. It follows each field's type, including number fields.
const checkoutDefinition = defineForm({
fields: {
quantity: { type: FieldDataType.Number, defaultValue: 1 },
},
});
type FormValues = InferFormValues<typeof checkoutDefinition>;
// { quantity: number }APIs
| API | Purpose |
| ----------------------------------- | -------------------------------------------------------------------- |
| defineForm(definition, options?) | Parse, validate, normalize, and clone a form definition. |
| serializeForm(form) | Return JSON-safe data and omit runtime-only registries. |
| deserializeForm(input, options?) | Parse a JSON string or unknown value into a normalized runtime form. |
| toValibotSchema(form) | Compile the form into a Valibot object schema. |
| toTanStackOptions(form, options?) | Generate default values and validators.onSubmit for TanStack Form. |
| getDefaultValues(form) | Extract cloned default values from each field. |
| createRendererRegistry(registry) | Create named and type-based renderer lookup tables. |
| resolveRenderer(field, registry) | Resolve a field renderer by component, then by field type. |
| createValidatorRegistry() | Register named custom validators used by JSON definitions. |
Typed JSON Restoration
JSON has no TypeScript type information, so deserializeForm(json) cannot infer a
specific value shape from an unknown string or value. When the stored data is known
to match a code-authored definition, supply that definition type explicitly:
const knownDefinition = defineForm({
fields: {
quantity: { type: FieldDataType.Number, defaultValue: 1 },
},
});
const json = JSON.stringify(serializeForm(knownDefinition));
const restored = deserializeForm<typeof knownDefinition>(json);
type FormValues = InferFormValues<typeof restored>;
// { quantity: number }Use this assertion only when the source of the JSON is trusted to follow the known
definition. deserializeForm still validates every loaded value at runtime.
Renderer Keys
Core stores renderer keys, not framework components. Passing renderers to defineForm or deserializeForm is optional and mainly useful for component-name type narrowing and for carrying runtime registries alongside a normalized form object.
import { createRendererRegistry, FieldDataType, resolveRenderer } from '@tgb-form/core';
const renderers = createRendererRegistry({
byName: {
'email-input': EmailInput,
},
byType: {
[FieldDataType.String]: TextInput,
[FieldDataType.Boolean]: CheckboxInput,
},
});
const Renderer = resolveRenderer(form.fields.email, renderers);An explicit component must exist in byName. Fields without component fall back to byType[field.type].
Custom Validators
Custom validators keep code out of JSON. The definition stores a name; runtime code supplies the Valibot compiler.
import * as v from 'valibot';
import { createValidatorRegistry, defineForm, FieldDataType } from '@tgb-form/core';
const validators = createValidatorRegistry().register('companyEmail', ({ message }) =>
v.check((value: string) => value.endsWith('@example.com'), message),
);
const form = defineForm(
{
fields: {
email: {
type: FieldDataType.String,
defaultValue: '',
validators: [{ name: 'companyEmail', message: 'Use a company email' }],
},
},
},
{ validators },
);