Welcome Guest, Not a member yet? Register   Sign In
Validating rules based on multiple fields in the form validator
#1

[eluser]rohanprabhu[/eluser]
When we use the form validator to set rules, we set those rules for a certain 'field'. For ex:

Code:
$this->form_validation->set_rules('username', 'Username', 'required');

asserts that the 'username' field must not be empty. However, i need to have a validation rule which performs authentication. Let's say this function is called 'perform_auth'. However, if i use it as a callback function:

Code:
$this->form_validation->set_rules('username', 'Username', 'callback_perform_auth');

this results in function call of the format:

Code:
Object::perform_auth($username)

i.e. i'm able to pass only one parameter to the function.. not both the username and password. My only need is to be able to set an error message if the username/password don't match:

Code:
$username = $this->input->post('username');
$password = $this->input->post('password');

if($this->auth->perform_auth($username, $password) == false) {
    $this->form_validation->set_message('upass_fail', "Username/Password don't match");
}

The above mentioned code doesn't work.. If i do <?php echo(validation_errors()); ?>, nothing is shown at all.. how do I go around this?

thanks,
rohan
#2

[eluser]Michael Wales[/eluser]
Code:
// Note the double underscore, making our validation function private
$this->form_validation->set_rules('username', 'Username', 'callback__perform_auth');

Code:
function _perform_auth($username) {
  $password = $this->input->post('password');
  if ($this->auth->perform_auth($username, $password) === FALSE) {
    $this->form_validation->set_message('_perform_auth', "Username/Password don't match.");
    return FALSE;
  }
  return TRUE;
}
#3

[eluser]rohanprabhu[/eluser]
hey.. that solved the problem.. thanks a lot Big Grin
#4

[eluser]rohanprabhu[/eluser]
i'm having another problem now.. Assuming these are my rules:

Code:
$this->form_validation->set_rules('username', 'Username', 'required|min_length[6]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|callback__perform_auth');

Now, if the user puts in an empty username, the error messages are:

Quote:The username field is required
Wrong username/password entered

It's obvious that the username/password is wrong if the username doesn't confirm to the input requirements. I want the system to check for the username/password only and only if the input is correct. How do I go about doing this?
#5

[eluser]Thorpe Obazee[/eluser]
check if the username field is empty before attempting to perform the logic in your callback.




Theme © iAndrew 2016 - Forum software by © MyBB