Home > Software engineering >  Codeigniter 4 - Apply validation rules without making the fields required
Codeigniter 4 - Apply validation rules without making the fields required

Time:04-11

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

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 required, 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 the 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 >
        <div >
            <div >
                <?= 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" >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",

CodePudding user response:

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 ...
}

CodePudding user response:

I just noticed that the following examples: "mylink", "mylink.com", "https://www.mylink.com" will consider correct for the rule valid_url in Codeigniter (No errors), While: "https:://www.mylink.com", "mylink@" will apply the validation and the error is applied.

  • Related