Jorz
Jorz

Reputation: 358

Codeigniter Form-Validation: Validate if input is equals to a certain string

I just need a validation on how to check if user input is equals to a certain string.

public function check_input()
{
   $input_str = $this->input->post("input_str", TRUE);

   $this->form_validation->set_rules("input_str, "Input String", "trim|required| validate if $input_str is equals to the string 'FOO' ");

   if ($this->form_validation->run() == FALSE)
   {
       // if input_str != 'FOO', do something
   }
   else
   {
       // do something
   }
}

Upvotes: 0

Views: 1418

Answers (2)

sauhardnc
sauhardnc

Reputation: 1961

You need to make a callback function and then check if the value is equal to 'foo' or not, you'll also need to change the case to lower so that if user writes uppercase it doesn't pose any error. I've written a possible solution for your problem, comments are mentioned wherever necessary. See if it helps you.

public function check_input(){

    $this->form_validation->set_rules("input_str", "Input String", "trim|required|callback__checkstring"); // call to a function named _checkstring

    if ($this->form_validation->run() == FALSE){

        // if input_str != 'FOO', do something
    }
    else{

        // do something
    }
}

function _checkstring(){

    $input_str = strtolower($this->input->post("input_str", TRUE)); // get the post data and convert it to lowercase

    if($input_str !== 'foo'){

        $this->form_validation->set_message('_checkstring','Please enter the correct value!');  //set message to the callbacked function(ie _checkstring) not the input field here.
        return FALSE;

    }else{

        return TRUE;
    }
}

Upvotes: 1

kirb
kirb

Reputation: 369

You can make a function to filter the word, and

public function username_check($str)
{
    if ($str == 'test')
    {
        $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

and call it in your set_rules

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

For more information you can check the documentation page https://codeigniter.com/userguide3/libraries/form_validation.html#callbacks-your-own-validation-methods

Upvotes: 0

Related Questions