Search code examples
phpcodeignitercodeigniter-4

Codeigniter 4 Validation for optional values


How to validate optional values in codeigniter 4

for example conditions

  1. If one field is filled by user which is an optional
  2. If one field is left empty by user which is an optional

how should I validate in first condition

This is my model code where I want phone field to be optional

'create' => [
            'message'               => 'required|alpha_numeric_punct|max_length[10000]',
            'name'                  => 'required|alpha_space',
            'email'              => 'required|valid_email',
            'phone'                 => 'alpha_numeric_punct',           
            'status'                => 'required|integer',
        ],

Solution

  • You can use permit_empty which Allows the field to receive an empty array, empty string, null or false.

    in your model code

    'create' => [
                'message'               => 'required|alpha_numeric_punct|max_length[10000]',
                'name'                  => 'required|alpha_space',
                'email'                 => 'required|valid_email',
                'phone'                 => 'permit_empty|alpha_numeric_punct',           
                'status'                => 'required|integer',
            ],
    

    for more validation rules please follow documentation

    Hope this answer helps you.