I have these issue where I want to set a rules on three input forms of type "text", my rule is that at least one of these three has values (either of the three), I have no idea how to set them in CI, because they are altogether executed when run() is triggered, any on of you guys knows how to set these kind of rules to form validation in CI please do share your knowledge.
1 Answer
You can set your own type of validation functions. It is pretty well documented here, but an excerpt would be:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
callback_username_check is calling the username_check function in the controller
To answer your latest comment
// $data is $_POST
function my_form_validator($data)
{
$data = 'dont worry about this';
// you have access to $_POST here
$field1 = $_POST['field1'];
if($field1 OR $field2 OR $field3)
{
// your fields have value
return TRUE;
}
else
{
// your fields dont have any value
$this->form_validation->set_message('field1', 'At least one of the 3 fields should have a value');
return FALSE;
}
}
11 Comments
lemoncodes
i don't see how do it allow 3 inputs even though only 1 of the 3 has a value
lemoncodes
ohh so thats how it goes, imma try this one
lemoncodes
if thats the case, it can be passed an extra data, so where doest field2 and 3 came from? field1 is the only form name passed at the 1st params of setmessage
lemoncodes
hmm you have a point there though.. but how then can you validate that concatenated word?, all i know is passing the input name from the input html tag usiing CI's form validation ofcourse
meewog
I just tested, in your
my_form_validator() class, you have access to the $_POST array. Should be no problem accessing all of your form field values. |