Codeigniter 4 – Form Validation with Example

Validation Rules

- Required: required
- Valid Email: valid_email
- Min Length: min_length[5]
- Max Length: max_length[10]
- Exact Length: exact_length[5]
- Alpha: alpha
- Alpha Numeric: alpha_numeric
- Numeric: numeric
- Integer: integer
- Decimal: decimal
- Greater Than: greater_than[5]
- Less Than: less_than[10]
- In List: in_list[1,2,3]
- Matches: matches[password]

Using Validation Rules

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

Example:

namespace App\Validation;

use CodeIgniter\Validation\Validator;

class UserValidation extends Validator
{
    public $rules = [
        'name' => 'required|min_length[5]|max_length[10]',
        'email' => 'required|valid_email',
        'password' => 'required|min_length[8]',
        'confirm_password' => 'required|matches[password]',
    ];
}

Customizing Error Messages

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

Example:

$validation->setErrorMessages([
    'name' => [
        'required' => 'Name is required',
        'min_length' => 'Name must be at least 5 characters',
        'max_length' => 'Name must not exceed 10 characters',
    ],
]);

Validating Data

- Use the validate() method to validate data.

Example:

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

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

Note: Validation data 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