3

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',
        ],
WebRTClerni
  • 149
  • 1
  • 8

1 Answers1

6

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.

asimdev
  • 705
  • 1
  • 8
  • 22