Error Handeling
ForgeForm is designed to provide clear and actionable error feedback to users, enhancing form usability.
Contents
Error Handling in ForgeForm
- Defining Custom Error Messages: Tailoring error messages within your schema to be user-friendly and context-specific.
- Accessing Validation Errors: Retrieving and displaying error messages generated by ForgeForm's validation engine.
- Wizard Form Error Handling: Managing errors within multi-step wizard forms, including step-specific errors and lifecycle callbacks.
Custom Error Messages in Schemas:
ForgeForm allows you to define custom error messages directly within your schema for each validation rule. This empowers you to provide more informative and user-centric error feedback instead of relying on generic default messages.
You can customize error messages for the following validation rules:
requiredErrorMessage: Message forrequired: truevalidation failure.minLengthErrorMessage: Message forminLengthvalidation failure (strings, arrays).maxLengthErrorMessage: Message formaxLengthvalidation failure (strings, arrays).minErrorMessage: Message forminvalidation failure (numbers, dates).maxErrorMessage: Message formaxvalidation failure (numbers, dates).formatErrorMessage: Message for built-in format validations (e.g.,email,url,tel).patternErrorMessage: Message forpattern(regex) validation failure.customErrorMessage: Message for failures fromcustomValidatorfunctions.
If you do not provide custom error messages, ForgeForm will use sensible default error messages.
Example: Schema with Custom Error Messages:
In this customMessageSchema:
- Each field uses specific error message attributes (e.g.,
requiredErrorMessage,formatErrorMessage,minErrorMessage,maxLengthErrorMessage) to define user-friendly messages. - If validation for
firstNamefails because it's required, the error message will be "Please tell us your first name.". - For
emailAddress, if it's missing, the error is "Your email is needed to contact you."; if it's in the wrong format, the error is "Please enter a valid email format.".
2. Accessing Validation Errors:
ForgeForm's validate() method and forgeFormResolver provide structured validation results that include any errors encountered.
a) Accessing Errors from schema.validate():
When you use schema.validate(formData) directly (without React Hook Form), the method returns a ValidationResult object. If validation fails, validationResult.success will be false, and validationResult.errors will contain an object of errors.
In the validationResult.errors object:
- Keys are the field names (e.g., "email", "password").
- Values are error objects with properties:
error: The error message string (either your custom message or the default).type: The type of validation that failed (e.g., "required", "format", "minLength").
b) Accessing Errors with forgeFormResolver (React Hook Form):
When using forgeFormResolver with React Hook Form, errors are automatically populated into React Hook Form's formState.errors object. You access them directly within your React components:
React Hook Form's formState.errors object is structured similarly to validationResult.errors from schema.validate().
You can access error messages using paths like errors.username.message and errors.password.message in your JSX to display them next to the corresponding input fields.
3. Error Handling in Wizard Forms:
Error handling in Wizard Forms involves managing validation errors for each step and providing feedback as users navigate through the wizard.
a) Step Validation Errors:
When you call wizard.nextStep(stepData), it returns a Promise<boolean>.
- If the current step's validation passes, the
Promiseresolves totrue, and the wizard moves to the next step. - If validation fails, the
Promiseresolves tofalse. To get the specific validation errors for the step, you can callwizard.validateCurrentStep()afternextStepresolves tofalse.
b) onValidationError Callback in createWizard:
The createWizard function's options argument allows you to define an onValidationError callback. This callback is invoked whenever validation fails for a step during a nextStep call. It provides the stepId and the errors object for that step, allowing you to centralize error handling logic within your wizard.
Within the onValidationError callback:
stepId: The ID of the step where validation failed.errors: The validation error object for that step.
You can use this callback to log errors, display step-level error messages, or manage error states specific to each step in your wizard UI.
c) Displaying Errors in Wizard Forms:
In a Wizard Form UI, you typically want to display error messages:
- Near the Input Field: Displaying errors directly below or next to the input field that caused the error (as shown in React Hook Form examples).
- Step-Level Summary: Optionally, you might want to display a summary of errors at the top of a step if there are multiple errors, or to highlight which steps have errors in a step navigation bar.
You can use component state to manage and display step-specific error messages. When validation fails in nextStep or in the onValidationError callback, you can update the error state and conditionally render error messages in your step components.
Title
By using custom error messages in your schemas, accessing error details from validation results, and utilizing the onValidationError callback and step-level error management in Wizard Forms, you can create forms with excellent user feedback and a smooth error correction experience.
Understanding onValidationError Callback
As previously mentioned, the onValidationError callback, configured within the options of createWizard, is your central point for handling step validation failures in a Wizard Form. It's invoked automatically by ForgeForm whenever a call to wizard.nextStep() results in validation errors for the current step.
Parameters of onValidationError:
stepId: string: This parameter provides the unique identifier (id) of the wizard step that failed validation. This is crucial for identifying which step has errors, especially in multi-step wizards, allowing you to apply step-specific error handling or UI updates.errors: FormErrors: This parameter is the core of the error information. It's an object (FormErrors) containing the validation errors for the step. The structure of this object mirrors your schema's field structure for that step. For example:
Within the errors object:
- Keys are the field names that have validation errors.
- Values are error objects with:
type: Indicates the type of validation that failed (e.g.,'required','minLength','customValidator').error: The user-friendly error message string (customized or default).
Practical Uses of onValidationError Callback:
- Centralized Error Logging: The callback is a good place to log validation errors for debugging or monitoring purposes.
Displaying Step-Level Error Summaries:
You can use onValidationError to trigger the display of a summary message at the top of the step to inform the user that there are errors to correct within the current step.
Managing Step-Specific Error States:
The most common and powerful use of onValidationError is to update component state to manage and display errors directly within each step component. This allows you to associate specific error messages with their corresponding input fields.
Strategies for Displaying Errors in Wizard Form UI:
There are two primary strategies for displaying errors in Wizard Forms:
a) Near-Field Error Display:
This is the most user-friendly approach. Display error messages right next to or below the input field that caused the error. This provides immediate context and makes it easy for users to identify and correct mistakes.
Implementation: To achieve near-field error display, you'll typically use component state to store errors for the current step. When onValidationError is triggered, you parse the errors object and update your component's state to reflect these errors. Then, within your step component's JSX, you conditionally render error messages based on this error state, typically adjacent to the input fields.
Example (Conceptual - using React state in a step component):
In this conceptual example:
stepErrorsstate is used within the step component to hold errors relevant to this specific step.- When
onValidationErroris triggered in the parent wizard component, it would update state in the parent (e.g., acurrentStepErrorsstate) and potentially pass down relevant errors to each step component as props or using context. - Within
Step1Component,stepErrors.name && <p...>conditionally renders the error message next to the "name" input if there's an error for the "name" field.
b) Step-Level Error Summary (Optional Enhancement):
For longer forms or wizards with multiple fields per step, you can additionally provide a step-level error summary at the top of the step (as shown in the previous "Step-Level Error Summaries" example above). This summary acts as a quick overview to alert the user that there are problems on the current step. However, near-field error display is generally more important for usability.
Example: Integrating onValidationError with Step-Specific Error State (Conceptual Wizard Component)
Here's a conceptual outline of a wizard component demonstrating how to use onValidationError to manage step-specific error state and display near-field errors:
In this outline:
- The main
MyWizardFormComponentcomponent maintainsstepErrorsstate to hold errors for the currently active step. - The
onValidationErrorcallback updatesstepErrorsstate with the errors object received. onValidationSuccessandhandlePreviousare updated to clear thestepErrorsstate when validation succeeds or when navigating backward.- Step components (like
Step1Component) receivestepErrorsas props. - Within step components,
stepErrorsprop is used to conditionally render error messages next to the appropriate input fields (near-field error display).
By combining the onValidationError callback with step-specific error state management, you can create Wizard Forms that provide robust error handling and a clear, user-friendly error correction experience.