Codeigniter 4 – Creating Form for Validation with Example

Creating a Form

- Create a new file in the app/Views directory.
- Use HTML to create the form.

Example:

<form action="<?= site_url('form/submit') ?>" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" name="email" id="email"><br><br>
    <input type="submit" value="Submit">
</form>

Creating a Validation Class

- Create a new file in the app/Validation directory.
- Extend the CodeIgniter\Validation\Validator class.

Example:

namespace App\Validation;

use CodeIgniter\Validation\Validator;

class FormValidation extends Validator
{
    public $rules = [
        'name' => 'required',
        'email' => 'required|valid_email',
    ];
}

Using the Validation Class

- Use the validate() method to validate the form data.

Example:

public function submit()
{
    $validation = new FormValidation();
    if (!$validation->validate($_POST)) {
        // Validation failed
    } else {
        // Validation passed
    }
}

Customizing Error Messages

- Use the setErrorMessages() method to customize error messages.

Example:

$validation->setErrorMessages([
    'name' => [
        'required' => 'Name is required',
    ],
    'email' => [
        'required' => 'Email is required',
        'valid_email' => 'Invalid email',
    ],
]);

I hope this helps! Let me know if you have any further questions or need more information.

Note: Creating a form for validation class in CodeIgniter 4 provides a simple and intuitive way to validate user input. It helps to improve the security and reliability of your application.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0