How Validation Works

The Form Engine validation system provides a flexible, extensible way to define and execute validation rules for form fields. First-party validators use Zod Mini and registrations remain provider-neutral through Standard Schema.

Core Concepts

Validation Rules

Validation rules are plain JavaScript objects that describe how to validate a field value. This makes them JSON-serializable and perfect for form configurations:

Complete elements still need $type, id, and name when you paste configs into an engine.

{ type: 'required', message: 'This field is required' }

{ type: 'email', message: 'Please enter a valid email' }

{ type: 'minLength', value: 3, message: 'Must be at least 3 characters' }

ValidationRegistry

The ValidationRegistry is the central hub that manages all validation logic:

  • Stores validation implementations - Each validation type is a registration ($type, schema, metadata) with a handler function, held in a read-only registry
  • Converts rules to Zod Mini schemas - JSON rules become executable validators
  • Takes custom registrations at engine creation - Pass your own rules to createFormEngine({ validations: [...] })

Rule-to-Schema Generation

The system automatically converts validation rules into Zod Mini schemas:

const rules = [{ type: 'required' }, { type: 'email' }, { type: 'minLength', value: 5 }];

const schema = createZodSchemaFromRules(rules);

Basic Usage

Method 1: Direct JSON Rules

Perfect for form configurations and when you need maximum flexibility:

const emailField = {
	id: 'input',
	name: 'email',
	label: 'Email Address',
	rules: [
		{ type: 'required', message: 'Email is required' },
		{ type: 'email', message: 'Please enter a valid email address' },
	],
};

Method 2: Using Validation Presets

Great for programmatic usage and reducing boilerplate:

const emailRules = [
	ValidationPresets.string.required('Email is required'),
	ValidationPresets.string.email('Please enter a valid email address'),
];

Creating Schemas

Convert rules to Zod Mini schemas for validation:

const rules = [
	{ type: 'required', message: 'Password is required' },
	{ type: 'minLength', value: 8, message: 'Password must be at least 8 characters' },
	{
		type: 'pattern',
		value: '(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)',
		message: 'Password must contain uppercase, lowercase, and numbers',
	},
];

const schema = createZodSchemaFromRules(rules);

const result = schema.safeParse('mypassword123');
if (!result.success) {
	console.log('Validation errors:', result.error.issues);
}

Form Integration

Individual Field Validation

Define validation rules directly in field configurations:

const formConfig = {
	id: 'user-profile',
	title: 'User Profile',
	steps: [
		{
			id: 'personal-info',
			title: 'Personal Information',
			elements: [
				{
					id: 'input',
					name: 'firstName',
					label: 'First Name',
					rules: [
						{ type: 'required', message: 'First name is required' },
						{ type: 'minLength', value: 2, message: 'First name must be at least 2 characters' },
						{ type: 'maxLength', value: 50, message: 'First name cannot exceed 50 characters' },
					],
				},
				{
					id: 'input',
					inputType: 'email',
					name: 'email',
					label: 'Email Address',
					rules: [
						{ type: 'required', message: 'Email is required' },
						{ type: 'email', message: 'Please enter a valid email address' },
					],
				},
				{
					id: 'input',
					inputType: 'number',
					name: 'age',
					label: 'Age',
					rules: [
						{ type: 'required', message: 'Age is required' },
						{ type: 'min', value: 18, message: 'You must be at least 18 years old' },
						{ type: 'max', value: 120, message: 'Please enter a valid age' },
					],
				},
			],
		},
	],
};

Full Form Schema Generation

Generate a complete Zod Mini schema for the entire form:

const formSchema = generateFormSchema(formConfig.steps[0].elements);

const formData = {
	firstName: 'John',
	email: 'john@example.com',
	age: 25,
};

const result = formSchema.safeParse(formData);
if (result.success) {
	console.log('Form is valid:', result.data);
} else {
	console.log('Validation errors:', result.error.issues);
}

Validation Categories

The validation system organizes validators by category:

String Validations

  • required - Field must have a value
  • email - Valid email address format
  • url - Valid URL format
  • minLength / maxLength - String length constraints
  • pattern - Regex pattern matching
  • uuid - UUID format validation
  • phone - E.164 phone number format

Phone-input integrations replace the core phone handler with their own libphonenumber-based validator on the element registration (validations + defaultFor). Creating a form engine with that element stores the replacement handler in the engine's validation registry and applies the rule to phone-input fields. @schema-engine/forms does not depend on a phone-number library.

Number Validations

  • min / max - Numeric range validation

Array Validations

  • minItems / maxItems - Array length constraints

Network & Format Validations

  • ipv4 / ipv6 - IP address validation
  • cidr - CIDR range validation (version?: 'v4' | 'v6')
  • jwt - JWT token validation
  • hash - Hash format validation
  • base64 - Base64 encoding validation
  • cuid / cuid2 / ulid / hex - Identifier and hexadecimal formats

Date & Time Validations

  • datetime - ISO datetime validation
  • date - Date validation
  • time - Time validation

The async rule performs server-side validation with optional debouncing, caching, and cross-field dependencies.

Error Handling

Validation Error Structure

Zod Mini provides detailed error information:

const result = schema.safeParse(invalidData);
if (!result.success) {
	result.error.issues.forEach((error) => {
		console.log(`Field: ${error.path.join('.')}`);
		console.log(`Message: ${error.message}`);
		console.log(`Code: ${error.code}`);
	});
}

Form configuration errors

The errors above are about a field's value. A form's configuration (a width that does not exist, a recipe that is not registered, a rule with no handler) is checked by engine.validateForm, which throws a FormValidationError listing the problems it found. Each issue has a message and the path of the config key it is about, so you can point at the mistake without parsing English:

Problempath
The third field of step 1 has grid.width: halve['steps', 0, 'elements', 2, 'grid', 'width']
A fieldset child uses a rule with no handler['steps', 0, 'elements', 1, 'elements', 0, 'rules', 0, 'type']
view.$type is not a registered recipe['view', '$type']
A problem with the whole form[]

error.message has one line per issue, <path>: <message>, with array indexes in brackets and the id of each element or step the path passes:

steps[0] (contact).elements[2] (email).grid.width: Expected one of full, three-quarters, two-thirds, half, third, quarter.
view.$type: Unknown view recipe 'nope'. Register it with createFormEngine({ recipes: [...] }).

An issue a schema reported also has a code and params (for example too_small with { minimum: 3 }), so an editor can localize the diagnostic instead of showing the English message. An issue the engine finds itself has neither. A union that fails is reported at the key that failed in the branch the value was closest to, or at the union when no branch is.

A malformed form envelope (its own shape, such as steps not being an array) stops the deeper checks and is reported alone. An unrecognized key is reported at the key itself, for example ['view', 'shell', 'bogus'].

Use engine.safeValidateForm when you would rather branch on a result than catch:

import { formatIssuePath } from '@schema-engine/forms';

export function loadForm(json: unknown) {
	const result = engine.safeValidateForm(json);
	if (!result.success) {
		for (const { path, message } of result.issues) {
			console.error(`${formatIssuePath(path) || '(form)'}: ${message}`);
		}
		return undefined;
	}
	return result.data; // the same frozen NormalizedFormConfig validateForm returns
}

The { message, path } shape is a Standard Schema issue, so a YAML loader or an editor can map each path to a line or a field. FormRenderer and the Radiant provider call validateForm, so an invalid config thrown at render time shows the same lines in the error message.

Custom Error Messages

Always provide user-friendly error messages:

{ type: 'minLength', value: 8, message: 'Password must be at least 8 characters long' }

{ type: 'minLength', value: 8, message: 'Invalid input' }

Enhanced Async Validation

The Form Engine includes a powerful async validation system with caching, dependency resolution, and comprehensive error handling:

{
  type: 'async',
  url: '/api/validate-username',
  method: 'POST',
  extraPayload: { source: 'profile' },
  dependencies: ['email'],
  expectedResponse: { valid: true },
  debounce: 500,
  cacheTTL: 300000,
  disableCache: false,
  message: 'Username is already taken'
}

Key Features

The enhanced async validation system provides:

  1. Intelligent Caching - Reduces server load with configurable TTL
  2. Dependency Resolution - Automatic cross-field validation with dependsOn objects
  3. Request Optimization - Debouncing prevents excessive API calls
  4. Error Recovery - Graceful handling of network failures
  5. Memory Management - Expired entries are evicted during cache reads and writes

Dependency Resolution Process

When you specify dependencies, the system automatically:

  1. Monitors dependency fields for changes
  2. Creates dependsOn object with actual field values:
    {
    	"value": "userInput",
    	"dependsOn": {
    		"username": "actualUsername",
    		"email": "actual@email.com"
    	}
    }
  3. Re-validates dependent fields when dependencies change
  4. Caches results based on complete request payload

Performance Optimization

The async validator will:

  1. Debounce requests - Wait for user to stop typing before making API calls
  2. Cache responses - Store results to avoid duplicate requests (5min default TTL)
  3. Handle failures gracefully - Shorter cache TTL for errors (1min for HTTP errors, 30s for network)
  4. Clean up memory - Expired entries are evicted during cache reads and writes

Best Practices

1. Use JSON-Serializable Rules

Form configurations should use plain objects:

const formConfig = {
	rules: [
		{ type: 'required', message: 'Field is required' },
		{ type: 'email', message: 'Invalid email format' },
	],
};

const nonSerializableRule = {
	rules: [{ type: 'custom', validator: (value) => value.includes('@') }],
};

Pass executable custom validators to createFormEngine({ validations }); functions do not belong in a JSON form configuration.

2. Provide Clear Error Messages

Users need to understand what went wrong:

{ type: 'minLength', value: 8, message: 'Password must be at least 8 characters long' }

{ type: 'minLength', value: 8, message: 'Too short' }

3. Combine Multiple Validations

Layer validation rules for comprehensive checking:

const passwordRules = [
	{ type: 'required', message: 'Password is required' },
	{ type: 'minLength', value: 8, message: 'Password must be at least 8 characters' },
	{
		type: 'pattern',
		value: '(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)',
		message: 'Password must contain uppercase, lowercase, and numbers',
	},
];

4. Use Presets for Consistency

Leverage presets to maintain consistency across your application:

const emailRules = [
	ValidationPresets.string.required('Email is required'),
	ValidationPresets.string.email('Please enter a valid email address'),
];

Next Steps

The validation system provides a solid foundation for ensuring data quality while maintaining flexibility. The JSON-based approach makes it easy to configure complex validation scenarios while keeping your form definitions clean and maintainable.