Mangesh Sathe
Mangesh Sathe

Reputation: 2177

How to use same callback function for multiple text fields in codeigniter

I want to check if value is other than integer and float, i have written form validation as follows,

$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type');

and common call back function for all text filed is money_type()

    public function money_type($charge)
        {
            if (is_float($charge) == false && is_int($charge) == false && $charge >= 0)
            {
                $this->form_validation->set_message('{WHAT TO ENTER HERE}', 'Enter valid charges for space.');
                return FALSE;
            }
        else
        {
            return TRUE;
        }
    }

How can I find out during validation that {WHAT TO ENTER HERE}? field name is either of charge_hour, charge_day, charge_weekly, charge_monthly at runtime? so that form validation will show different error messages for each field.

Thanks.

Upvotes: 3

Views: 639

Answers (3)

Disha V.
Disha V.

Reputation: 1864

$this->form_validation->set_message('money_type','%s my message');

https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Upvotes: 2

Mangesh Sathe
Mangesh Sathe

Reputation: 2177

I got the answer, my mistake here.

{WHAT TO ENTER HERE} Should be same as callback function name function money_type , then it will work for all fields callbacks

$this->form_validation->set_message('{WHAT TO ENTER HERE}', 'Enter valid charges for space.');

Should be

$this->form_validation->set_message('money_type', 'Enter valid charges for space.');

Upvotes: 0

Saty
Saty

Reputation: 22532

You can pass your file name in your callback parameter

$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type[charge_hour]');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type[charge_day]');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type[charge_weekly]');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type[charge_monthly]');

You callbacke function

public function money_type($charge,$fild_name)
        {
            if (is_float($charge) == false && is_int($charge) == false && 

    $charge >= 0)
                {
                    $this->form_validation->set_message("{$fild_name}", 'Enter valid charges for space.');
                    return FALSE;
                }
            else
            {
                return TRUE;
            }
        }

Upvotes: 1

Related Questions