Logic

Form Controller API

Detailed documentation for the FormController, its methods, configuration, state management, and validation capabilities.

API Reference

Comprehensive documentation of Form Controller's API and capabilities.

Controller Methods

The FormController instance provides a set of methods to interact with and manage the form. These methods are available under the methods property of the controller object, or directly if using a framework-specific binding.

FormController Methods API

The methods below provide programmatic control over form state, validation, navigation, and configuration. They're designed for both reactive UI integration and imperative control flow.

1// Basic FormController usage
2import { FormController } from "@uplink-protocol/form-controller";
3
4// Initialize the controller with configuration
5const formController = FormController(myFormConfig);
6
7// Access methods
8const { methods } = formController;
9
10// Example: Navigate to the next step
11methods.nextStep();
12
13// Example: Submit the form
14const result = methods.submitForm();
15if (result.success) {
16 console.log("Form data:", result.data);
17} else {
18 console.log("Validation errors:", result.errors);
19}

Navigation

Methods to move between form steps, supporting multi-step form workflows.

Data Management

Functions for handling form data, including field operations and form-wide data access.

Validation

Methods to validate fields, steps, or the entire form programmatically.

Navigation Methods

nextStep

1nextStep: () => number;

Advances the form to the next step in a multi-step form workflow. This method handles all the logic for step transitions, including validation of the current step if configured to do so. If the form is already at the last step, this method will have no effect and return the current index.

Returns:

number - The index of the new current step after navigation. Use this to update UI elements that depend on the current step.

prevStep

1prevStep: () => number;

Navigates back to the previous step in a multi-step form. This method handles backward navigation safely, preserving all previously entered data. If the form is already at the first step (index 0), this method will have no effect and return 0.

Returns:

number - The index of the new current step after navigation. Returns 0 if already at the first step.

goToStep

1goToStep: (stepIndex: number) => boolean;

Directly navigates to any step in the form by its index. This method provides flexible navigation beyond simple next/previous operations, allowing for non-linear form flows such as skip logic or branching paths. The method includes boundary checks to prevent navigation to non-existent steps.

Parameters:

  • stepIndex(number): The 0-based index of the target step to navigate to. Must be a valid index in the steps array.

Returns:

boolean - True if navigation was successful, false if the target index was invalid or navigation was prevented for any reason.

Field Management Methods

updateField

1updateField: (stepId: string, fieldId: string, value: any) => void;

Updates the value of a specific field in the form. This is the primary method for programmatically changing form values. It triggers internal state updates, validation (if configured), and notifies any subscribers of the state change. This is the recommended way to change field values rather than directly manipulating state.

Parameters:

  • stepId(string): The unique ID of the step containing the target field, as defined in your form configuration.
  • fieldId(string): The unique ID of the field to update within the specified step.
  • value(any): The new value to set for the field. The type should match the expected field type (string, number, boolean, object, etc.).

Validation Methods

validateField

1validateField: (stepId: string, fieldId: string, value?: any, showErrors?: boolean) => boolean;

Validates a single field against its configured validation rules. This method is useful for immediate validation feedback after field interaction, without waiting for form submission. You can optionally validate against a temporary value without updating the actual field data, which is useful for preview validation during typing.

Parameters:

  • stepId(string): The unique ID of the step containing the field to validate.
  • fieldId(string): The unique ID of the field to validate within the specified step.
  • value(any): Optional alternative value to validate instead of the current field value. Useful for validation previews or "what-if" scenarios.
  • showErrors(boolean): When true (default), validation errors will be stored in the fieldErrors state and can be displayed in the UI. Set to false to perform validation without updating the error state.

Returns:

boolean - True if the field passes all validation rules, false if any validation fails.

validateStep

1validateStep: (stepId: string, showErrors?: boolean) => boolean;

Validates all fields within a specified step. Errors can be shown or hidden.

Parameters:

  • stepId(string): The ID of the step to validate.
  • showErrors(boolean): (Optional) If true, updates fieldErrors state for fields in this step. Defaults to true.

Returns:

boolean - True if all fields in the step are valid, false otherwise.

validateCurrentStep

1validateCurrentStep: (showErrors?: boolean) => boolean;

Validates all fields in the current active step. Errors can be shown or hidden.

Parameters:

  • showErrors(boolean): (Optional) If true, updates fieldErrors state for fields in the current step. Defaults to true.

Returns:

boolean - True if the current step is valid, false otherwise.

validateCurrentStepWithTouchedErrors

1validateCurrentStepWithTouchedErrors: () => boolean;

Validates the current step, but only updates error messages for fields that have been 'touched' (interacted with or previously validated).

Returns:

boolean - True if the current step is valid based on touched fields, false otherwise.

validateStepWithTouchedErrors

1validateStepWithTouchedErrors: (stepId: string) => boolean;

Validates a specific step, but only updates error messages for fields within that step that have been 'touched'.

Parameters:

  • stepId(string): The ID of the step to validate.

Returns:

boolean - True if the specified step is valid based on touched fields, false otherwise.

validateForm

1validateForm: (showErrors?: boolean) => boolean;

Performs complete validation of all form fields across all steps. This comprehensive validation is typically used before form submission to ensure all data is valid. The method executes all configured validation rules including required fields, pattern matching, custom validators, and cross-field validations.

Parameters:

  • showErrors(boolean): When true (default), validation errors will be stored in the fieldErrors state and can be displayed in the UI. Set to false to check validity without updating error messages.

Returns:

boolean - True only if every field in every step passes all its validation rules. Returns false if any validation fails.

Form Action Methods

submitForm

1submitForm: () => { success: boolean; data?: Record<string, Record<string, any>>; errors?: Record<string, Record<string, string>> };

Executes the form submission process with built-in validation. This is the primary method to call when a user completes a form. It first performs validation on all fields using validateForm(). If validation passes, it returns the complete form data and triggers any onSubmit callback configured in the form. If validation fails, it returns detailed validation error information instead.

Returns:

{ success: boolean; data?: Record<string, Record<string, any>>; errors?: Record<string, Record<string, string>> } - A result object containing: 'success' flag indicating if submission was successful, 'data' containing all form values if successful, or 'errors' containing validation error messages if unsuccessful.

resetForm

1resetForm: () => void;

Completely resets the form to its initial state. This method clears all user-entered data, resets validation errors, and returns to the first step. Use this after successful form submission to allow the user to start over, or when implementing a 'Clear Form' feature. Any initialData provided in the original form configuration will be restored.

updateConfig

1updateConfig: (newConfig: FormConfig) => void;

Dynamically updates the form's configuration. This allows changing steps, fields, or other settings after the controller has been initialized.

Parameters:

  • newConfig(FormConfig): The new form configuration object.

Data Access Methods

getStepData

1getStepData: (stepId: string) => Record<string, any>;

Retrieves the data for a specific step.

Parameters:

  • stepId(string): The ID of the step.

Returns:

Record<string, any> - An object containing fieldId-value pairs for the specified step.

getAllData

1getAllData: () => Record<string, Record<string, any>>;

Retrieves all form data, structured by step ID and then field ID.

Returns:

Record<string, Record<string, any>> - An object where keys are step IDs, and values are objects of fieldId-value pairs for that step.

getFlatData

1getFlatData: () => Record<string, any>;

Retrieves all form data as a single flat object, where keys are field IDs. Note: If field IDs are not unique across steps, values might be overwritten.

Returns:

Record<string, any> - An object containing all fieldId-value pairs from the form.

Step Management Methods

addStep

1addStep: (step: FormStep, index?: number) => number;

Adds a new step to the form at a specified index. If no index is provided, the step is added at the end.

Parameters:

  • step(FormStep): The FormStep object to add.
  • index(number): (Optional) The 0-based index at which to insert the step.

Returns:

number - The new total number of steps.

removeStep

1removeStep: (stepId: string) => boolean;

Removes a step from the form by its ID.

Parameters:

  • stepId(string): The ID of the step to remove.

Returns:

boolean - True if the step was successfully removed, false otherwise (e.g., step not found).

Validator Methods

registerValidator

1registerValidator: (name: string, validatorFn: DynamicValidator) => void;

Registers a custom validator function with a unique name. This validator can then be referenced in field configurations.

Parameters:

  • name(string): A unique name for the validator.
  • validatorFn(DynamicValidator): The validator function. See Validation tab for DynamicValidator signature.

unregisterValidator

1unregisterValidator: (name: string) => boolean;

Removes a previously registered custom validator.

Parameters:

  • name(string): The name of the validator to unregister.

Returns:

boolean - True if the validator was successfully unregistered, false otherwise.

getAvailableValidators

1getAvailableValidators: () => string[];

Returns a list of all registered validator names, including built-in and custom validators.

Returns:

string[] - An array of validator names.