Trongate Website Homepage

Handling Form Validation Errors With Trongate MX

Trongate MX provides a seamless way to handle and display form validation errors in conjunction with the Trongate PHP framework. This guide will walk you through the process of setting up your forms to effectively handle and display validation errors using Trongate MX.

Setting Up Your Form

To properly handle form validation errors with Trongate MX, you need to structure your form correctly. Here's an example of a form that's set up to handle validation errors:

<form mx-post="tasks/submit_task" 
            mx-close-on-success="true" 
            mx-animate-success="true" 
            mx-animate-error="true"
            mx-on-success="#result" 
            mx-target="#response-message"
            autocomplete="off" class="highlight-errors">
    <label>Task Title</label>
    <div class="error-message"></div>
    <input type="text" name="task_title" placeholder="Enter title here..." autocomplete="off">
    <button type="submit">Submit</button>
<?= form_close() ?>
<style>
.error-message {
    color: red;
}
</style>

Key Components:

  1. Form Attributes:
    • mx-post: Specifies the endpoint for form submission.
    • mx-close-on-success: Closes the modal (if applicable) on successful submission.
    • mx-animate-success and mx-animate-error: Provide visual feedback for submission results.
    • mx-on-success: Specifies an element to update on successful submission.
    • mx-target: Defines where to display the server response.
    • class="highlight-errors": Enables inline error highlighting.
  2. Error Message Container: <div class="error-message"></div> - This div will contain field-specific error messages.
  3. Form Closing: <?= form_close() ?> - Uses Trongate's form helper to properly close the form and include CSRF protection.
  4. Error Styling: The included style block sets the color of error messages to red.

If all of the above seems a little overwhelming then perhaps it's worth taking a moment to step back and clarify what the example shown aims to achieve.

KEY POINTS ABOUT THE SAMPLE CODE

  • Our example, as described above, would be applicable for a form that is being displayed within a dynamic modal.
  • Upon successful form submissions:
    1. A 'success' animation would be displayed within the modal body.
    2. The animation would disappear after approximately 1.3 seconds.
    3. Thereafter, the modal that contains the form would automatically close.
    4. A list of records, displaying tasks would be automatically refreshed.
    5. A message containing the words, 'The task was successfully created' would be added onto the page, inside an element with an 'id' of 'response-message'.
  • Upon erroneous form submissions:
    1. The modal that contains the form would remain on the page.
    2. An 'error' animation would be displayed within the modal body.
    3. The animation would disappear after approximately 1.3 seconds.
    4. Thereafter, the form would re-appear but with inline validation errors clearly displayed.
    5. The data that the user has originally submitted would also be visible.
    6. The user would then have an opportunity to adjust the form details and try again.

This is certainly a vast amount of things happening for a relatively small amount of code!

View File Example

The code below demonstrates a view file that could be assumed to be on the page for our example:

<h1 class="text-center">Your Tasks</h1>
<div id="response-message"></div>
<p class="text-center">

<button mx-get="tasks/create_task" 
        mx-build-modal='{
            "id": "new-task-modal",
            "width": "760px",
            "showCloseButton": "true",
            "modalHeading": "Create New Task"
        }'>Create New Task
</button>

</p>
<div class="spinner mx-indicator"></div>
<div id="result" mx-get="tasks/view_all" mx-select="table" mx-trigger="load" mx-indicator="spinner"></div>

Server-Side Validation Example

On the server side, you'll need to set up validation rules and handle the form submission. Here's an example of how you might structure your controller method:

public function submit_task() {
    $this->validation->set_rules('task_title', 'Task Title', 'required|min_length[5]|max_length[255]');
    $result = $this->validation->run();
    if ($result === true) {
        // Process the valid form data
        $data = $this->get_data_from_post();
        $this->model->insert($data, 'tasks');
        $success_msg = 'The task was successfully created';
        http_response_code(200);
        echo $success_msg;
    } else {
        // Handle validation errors
        http_response_code(400);
        echo validation_errors(400);
    }
}

This method sets validation rules, runs the validation, and either processes the data or returns validation errors.

How Trongate MX Handles Validation Errors

When the server returns a 400 status code along with validation errors, Trongate MX automatically handles the display of these errors:

  1. Field-specific errors are displayed in the corresponding error-message divs.
  2. The highlight-errors class on the form enables inline error highlighting for affected fields.
  3. The mx-animate-error attribute triggers an error animation to provide visual feedback.

Customizing Error Display

You can customize the appearance of error messages using CSS. The example includes a basic style for error messages, but you can expand on this:

.error-message {
    color: red;
    font-size: 0.9em;
    margin-top: 5px;
}

.form-field-validation-error {
    border: 1px solid red;
}

.highlight-errors input.form-field-validation-error {
    background-color: #fff0f0;
}

Best Practices

  1. Always use form_close() to ensure proper CSRF protection.
  2. Include error message containers (div class="error-message") for each form field.
  3. Use the highlight-errors class on your form for inline error highlighting.
  4. Customize error styles to match your application's design.
  5. Use mx-animate-success and mx-animate-error for better user feedback.
  6. Ensure your server-side validation aligns with client-side expectations.

Conclusion

By leveraging Trongate MX's built-in error handling capabilities along with Trongate's server-side validation, you can create a robust and user-friendly form validation system. This approach provides immediate feedback to users, enhancing the overall user experience of your application. The combination of inline error messages, field highlighting, and animated feedback creates a responsive and intuitive form interaction.