Search code examples
codeignitercodeigniter-4

Codeigniter 4 - Apply validation rules without making the fields required for URL


I want to apply validation rules only for the input fields that are not empty (not required) for the URL

For example, If I submit a form and the input is empty, I got a validation error "Instagram Link must be valid URL.", However, I want it without requiring, and if the input is not empty, I want to apply the rule "valid_url"

How can we fix it?

if (!$this->validate([
        'instagram' => [
            'rules' => 'valid_url',
            'errors' => [
                'valid_url' => 'Instagram Link must be valid url.',
            ],
        ],
    ])){
        return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
    }

I tried with a permit_link rule, but if I submit it (with an input value like 'mylink' (which is not a valid_url)), it will accept it, but it should not.

Please check the following images and the code: A form HTML Result after clicking on edit button

<?= form_open('/settings/edit/1', ['id' => 'setting-form']); ?>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <?= form_label('Instagram'); ?>
                <?= form_input(['name' => 'instagram', 'class' => 'form-control', 'id' => 'instagram', 'placeholder' => 'Enter instagram link', 'value' => old('instagram', $setting->instagram)]); ?>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-dark">Edit</button>
    <?= form_close(); ?>


   public function edit($id)
{

    if (!$this->validate([
        'instagram' => [
            'rules' => 'permit_empty|valid_url',
            'errors' => [
                'valid_url' => 'Instagram Link must be valid url.',
            ],
        ],
    ])) {
        return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
    }

    die('submitted');
}

It should display "Instagram Link must be valid url" and not "submitted",


Solution

  • first

    Use separate variable $rules like this :

    $rules = ['data' => 'require']
    

    Then

    check if $this->request->getVar("instagram"); is empty / is true or etc.. then set it on the $rules

    finally

    Do Something like this :

    $rules = ['extra_data' => 'require'];
    
    if(!empty($this->request->getVar("instagram"))    
    $rules["instagram"] = "valid_url";
    
    if ($this->validate(rules){
        //do something ...
    }else {
        //do something ...
    }