CodeIgniter Forums

Full Version: [SOLVED! SOLUTION INSIDE] Form Validation class how to add your own rule
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]basementDUDE[/eluser]
I need a extremely simple function to test a number whether it is positive or not.
I have a hard time to get it to work in codeigniter.

This is what I did:
1) I add _is_positive function in my controller class

function _is_positive($num){
if($num > 0)
{
return true;
}else
{
return false;
}
}


2) then I call it like this:

$this->form_validation->set_rules('price', 'price', "trim|required|numeric|_is_positive[$price]");

even I give negative value to price variable it still take it...
and I do not think that will be a native php function...

El Forum

[eluser]pistolPete[/eluser]
Have a look at the userguide: form_validation.html#callbacks

Code:
$this->form_validation->set_rules('price', 'price', 'trim|required|numeric|callback__is_positive');

El Forum

[eluser]Tom Schlick[/eluser]
we should start a thread with all of the extra form validation functions we have (i know i have a bunch of custom ones) and release them as a MY_Form_Validation library. or better yet it will get some attention and hopefully some of them will be integrated into the core.

El Forum

[eluser]basementDUDE[/eluser]
thanks a lot pistolPete.

It works great after I change my code to this:

1)$this->form_validation->set_rules('price', 'price', "trim|required|numeric|callback_price_check");

2) function price_check($price){
if ($price < 0)
{
$this->form_validation->set_message('price_check', 'The %s field can not be less than 0');
return false;
}
else
{
return true;
}
}

El Forum

[eluser]basementDUDE[/eluser]
[quote author="trs21219" date="1249126052"]we should start a thread with all of the extra form validation functions we have (i know i have a bunch of custom ones) and release them as a MY_Form_Validation library. or better yet it will get some attention and hopefully some of them will be integrated into the core.[/quote]
that will be really nice Smile. Who do we contact for code review and submission?