Create New Post

Displaying validation errors

To display validation errors in CodeIgniter, you can use the validation_errors() function provided by the Form Validation Library. This function returns a string containing any validation errors that occurred during the form submission. You can then display these errors next to the corresponding form fields in your view. Here's how you can do it:

1. Display Validation Errors in the View:

  • Inside your view file (e.g., form_view.php), use the validation_errors() function to display validation errors.
 <!DOCTYPE html>
<html>
<head>
    <title>Form Submission</title>
</head>
<body>
    <h2>Submit Form</h2>
    <?php echo validation_errors(); ?> <!-- Display validation errors here -->
    
    <?php echo form_open('form/handle_submission'); ?>
    
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>">
    
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" value="<?php echo set_value('email'); ?>">
    
    <input type="submit" value="Submit">
    
    <?php echo form_close(); ?>
</body>
</html>

2. Explanation:

  • validation_errors() function returns a string containing any validation errors. If there are no errors, it returns an empty string.
  • You should call validation_errors() function where you want to display the validation errors in your view.
  • set_value() function is used to repopulate form fields with the data submitted by the user, allowing them to correct their mistakes easily.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

11133