kartik
kartik

Reputation: 603

Using is_unique validation rule with two fields?

I have two input fields in a form. I need to check if both of them are unique in a table in which they are inserted. How can I perform this check in codeigniter.

Upvotes: 2

Views: 2280

Answers (2)

Beno
Beno

Reputation: 1

create class as <?php

namespace App\Validation;

use CodeIgniter\Database\Exceptions\DataException;
use Config\Database;

class CustomRules
{
    /**
     * Check if a combination of fields is unique.
     *
     * Example usage: is_unique_combination[tbl_recruitmentEmailTemplates.emailTemplateName,companyId]
     *
     * @param string $str
     * @param string $fields
     * @param array  $data
     *
     * @return bool
     */
    public function is_unique_combination(string $str, string $fields, array $data): bool
    {
        list($table, $field1, $field2) = explode(',', $fields);

        if (!isset($data[$field2])) {
            throw new DataException("The second field in the unique combination check is missing in the data array.");
        }

        $db = Database::connect();
        $builder = $db->table($table);
        $builder->where($field1, $str);
        $builder->where($field2, $data[$field2]);

        return $builder->countAllResults() === 0;
    }
}
and register it in 
<?php
namespace Config;

use CodeIgniter\Validation\Rules;
use App\Validation\CustomRules;

class Validation extends \CodeIgniter\Config\BaseConfig
{
    public $ruleSets = [
        Rules::class,
        CustomRules::class,
    ];

    // Other existing code...`enter code here`
}
and use for validation as 
               'emailTemplateName' => 'required|min_length[3]|max_length[255]|is_unique_combination[tbl_recruitmentEmailTemplates,emailTemplateName,companyId]',

Upvotes: 0

umefarooq
umefarooq

Reputation: 4574

yes its really easy with CI form validation you need to set is_unique to check unique value in table

$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');

$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');

in above example you can see is_unique table name and column name of table to check unique value as parameter

here the document link you can read http://www.codeigniter.com/user_guide/libraries/form_validation.html#rulereference

Upvotes: 1

Related Questions