js

Monday, July 7, 2025

Explain "$this->form_validation->run()" in codeignitor


In CodeIgniter, the method $this->form_validation->run() is used to run the validation rules that you've set for form inputs. It checks whether the submitted form data passes all the validation rules you have defined using $this->form_validation->set_rules().


🔍 Syntax:

$this->form_validation->run();

✅ Return Value:

  • Returns TRUE if the form data passes all validation rules

  • Returns FALSE if any rule fails


💡 Basic Usage Example:

public function submit_form() {
    // Load the form validation library
    $this->load->library('form_validation');

    // Set validation rules
    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

    // Run validation
    if ($this->form_validation->run() == FALSE) {
        // If validation fails, reload the form view with errors
        $this->load->view('my_form');
    } else {
        // If validation passes, process the data (e.g., insert into DB)
        echo "Form submitted successfully!";
    }
}

📌 How It Works:

  1. You define rules for each form field (e.g., required, min_length, etc.)

  2. When the form is submitted, run() checks the posted data against the rules

  3. If any rule fails, it returns FALSE, and you can show error messages

  4. If all rules pass, you proceed to process the form data


📋 Common Rule Types:

  • required – Field must not be empty

  • min_length[5] – Minimum 5 characters

  • max_length[10] – Maximum 10 characters

  • valid_email – Must be a valid email

  • numeric – Only numbers allowed

  • matches[password2] – Must match another field


📝 Showing Error Messages in View:

In the view file:

echo validation_errors();

This will display all validation errors as a list.



No comments:

Post a Comment

Class 10 Maths Exercise 1.4 Assamese Medium

Class 10 Maths Exercise 1.4 Assamese Medium ā§§) āĻĻীā§°্āϘ āĻšā§°āĻŖ āύāϕ⧰াāĻ•āĻ•ৈ āϤāϞāϤ āωāϞ্āϞেāĻ– āϕ⧰া āĻĒā§°িāĻŽেāϝ় āϏংāĻ–্āϝাāĻŦোā§°ā§° āĻ•োāύāĻŦোā§°ā§° āĻĻāĻļāĻŽিāĻ• āĻŦিāϏ্āϤৃāϤি āĻĒā§°িāϏāĻŽাāĻĒ্āϤ (āϏাāĻŦāϧি)...