Codeigniter Form Validation Callback checking multiple fields - php

I have this controller set up for a login:
<?php
class Login extends Controller {
function __construct() {
parent::Controller();
$this->form_validation->set_error_delimiters('', '');
$this->output->enable_profiler(TRUE);
}
function index(){
redirect('/login/terminal');
}
function terminal() {
// terminal login
$this->form_validation->set_rules(array('username','password'), 'Username', 'callback_terminal_login_check[$username,$password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_header');
$this->load->view('login_terminal');
$data['version'] = $this->master->GetVersion();
$this->load->view('login_footer', $data);
} else {
redirect('/terminal');
}
}
function terminal_login_check($username,$password) {
// callback function to perform terminal login
if ($this->authentication->DoTerminalAuthentication($username,$password)) {
echo $username;
return TRUE;
} else {
$this->form_validation->set_message('terminal_login_check', 'Invalid');
return FALSE;
}
}
}
What I am looking at is the line that does the form validation callback >> $this->form_validation->set_rules(array('username','password'), 'Username', 'callback_terminal_login_check[$username,$password]');
I know this is not right. Basically what I want to do is check the username and password against the Authentication->DoTerminalAuthentication model to process the user's login. I want to pass the $username and $password form fields. Here is my form view if it helps:
<div id="title">Terminal Login</div>
<?php
if (validation_errors()) {
echo '<div id="error">' . validation_errors() . '</div>';
}
?>
<?=form_open('login/terminal');?>
<?=form_label('Username', 'username')?><br />
<?=form_input(array('id'=>'username','name'=>'username','value'=>set_value('username')))?><br />
<?=form_label('Password', 'password')?><br />
<?=form_password(array('id'=>'password','name'=>'password'))?><br />
<?=form_submit(array('name'=>'passwordsubmit','value'=>'Login >>'))?><br />
<?=form_close();?>

Use this in your controller to set your validation rules.
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|callback_terminal_login_check');
And a callback something like this. I'd use a model if you are comparing your post data to a database.
function terminal_login_check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
// LOAD MODEL HERE
if ($this->authentication->DoTerminalAuthentication($username, $password))
{
echo $username;
return TRUE;
}
else
{
$this->form_validation->set_message('terminal_login_check', 'Invalid');
return FALSE;
}
}
Edit 2013-07-09: Added required field to password validation rule so you don't have to hit the DB if someone doesn't add a password.

As I understand it, form validation works on a field by field basis. To achieve what you want, I would attach the callback to one of the fields (probably the password field would be best) and then access the other form field data using the global POST array. This way you don't need to pass anything to the callback function as parameters.

I prefer to use form validation for simple input validation like checking for empty fields, invalid email addresses, too short passwords etc. I tend not to use form validation for more complex logic like authentication. I'd put the authentication check in the action method rather than in a validation callback function. It would get past your particular problem by side-stepping it.
function terminal()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run())
{
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->authentication->DoTerminalAuthentication($username, $password))
{
// Handle successful login
}
else
{
// Authentication failed. Alert the view.
$this->load->view('terminal', array('login_failed' => true));
}
}
else
{
$this->load->view('terminal', array('login_failed' => false));
}
}
And then in the view you can place this below your login form
<?php if ($login_failed) : ?>
<span id="login-failed-message">Login failed</span>
<?php endif; ?>

Related

CI form validation

I'm developing a function that should enable users to update their personal information and I'm using CI form validation library. I'd want to know if what I'm doing is right.
public function updateDetails()
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
// Send to model
}
}
Is this right? Or is there another method to do this?
yes so far you're right
but you should process if the validation is successful
public function updateDetails()
{
// load the library if not already loaded in config/autoload.php
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
// Send to model
}
else
{
$data['error_message'] = "form not valid ...blablabla";
//go back to form
$this->load->view("form_vew",$data);
}
}

CodeIgniter: Why variable change after callback function? Am I using it the right way?

I'm currently using CodeIgniter. And after a form validation I used the function "set_rules" for check if the user's information is correct.
Otherwise, I tried to send 2 variable using the "callback" function but it seem that the second variable change its value when I use "callback" function. If in my form I fil it as:
Username = "test_username"
Password = "test_password"
In my function database,
$username will display "test_username"
$password will display "test_username,test_password".
I tried by this way:
function index()
{
$this->load->library('form_validation');
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->form_validation->set_rules('username', 'Username', 'trim|required', 'wrong or missing username');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database($username, $password)', 'wrong or missing password');
}
function check_database()
{
echo '$password'. '</br>'; //display => test_username
echo '$username'. '</br>'; // display => test_username,test_password
}
I tried to replace a few line of the higher code by:
function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required', 'wrong or missing username');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database['. $this->input->post($username). ','. $this->input->post($password), 'wrong or missing password'];
function check_database($password, $username)
{
echo '$password'. '</br>'; //display => test_username
echo '$username'. '</br>'; // display => test_username,test_password
}
But it's the same problem.
I didn't find the manual of the callback function on the CodeIgniter site. The second question I have is when I write
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database', 'wrong or missing password');
function check_database() //work only if I write check_database($password)
{
//blah blah blah
}
It pop me an error. Given I didn't find any manual of call_back function, I suppose that the callback function is use into a set_rules which is testing the password variable so I think that the call_back function will automatically sent the password variable to check_database() function.(That's why I need to put $password to the check_database prototype).
I've already find a solution but I'm just here for know what happen(I'm curious) ?
Does anyone can tell me why in the first and the second code, the second parameter of callback change once it is on the check_database() ?
And by the way can you confirm me if am I right for the last code ? More precisely when I say that the call_back function will automatically sent the password variable to check_database() ?
Thank's
PS: In the code I show you before, I voluntarily remove a part of the code to avoid you to read to much because I post is a bit longer I think.
The variable or value does not change. In codeigniter form validation, the callback first parameter supply the value.
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database[x]');
....
function check_database($str, $param1)
{
echo $str; // password
echo $param1; // x
}
If you wish to supply other input post param, this is easier:
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
function check_database($str)
{
$username = $this->input->post('username'); // same input post value
....
}
Hope this helps.
http://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Unable to redirect url with callback in codeigniter

I just create login class that check the valid user, after that user enter in his/her home section. But now i need to change the destination of the user's home conditionally, Unable to
attach switch case in url redirection.
Note: I think varibale not properly passed in function.Plz help me
My code as Follow:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('userp','',TRUE);
}
function index($dest)
{
$this->load->view('header');
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$data['msg'] = "";
$this->load->view('login',$data);
}
$this->load->view('footer');
}
function check_database()
{
//Field validation succeeded. Validate against database
$email = $this->input->post('email');
//query the database
$password= $this->input->post('password');
$result = $this->userp->login($email,$password);
if($result!==FALSE)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' =>$row->email,
'fname' =>$row->first_name,
'lname' =>$row->last_name,
'pic'=>$row->pic
);
$this->session->set_userdata('logged_in',$sess_array);
}
switch($dest){
case 'NULL':{
redirect('home','refresh');
break;
}
case 'part1':{
redirect('subhome','refresh');
break;
}
case 'part2':{
redirect('subhome1','refresh');
break;
}
default :{
redirect('mainhome','refresh');
break;
}
}
return TRUE;
}
else
{
$data['msg'] = "Something Wrong Username/Password";
$this->load->view('login',$data);
//return false;
}
}
};
?>
The problem is that you are passing $dest to the index() function but you are attempting to use it in your check_database() function. So either you want to move your switch into the index function or you want to pass $dest to check_database() like
function check_database($dest)
{
//You can use $dest in here
}
If you want to pass an extra parameter to your callback function you need to put it in brackets like
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database[parameter]');
or
$this->form_validation->set_rules("password", "Password", "trim|required|xss_clean|callback_check_database[$parameter]");

Validating Forms

I have a form that I submit with jQuery ajax and have it being sent to a controller function called submit to validate and do any other tasks I need to with the form data. I'm trying to find out why my form validation library isn't showing an error when the username doesn't contain only lowercase letters and numbers.
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|strtolower');
POST Value after form submission:
username TestingUSER
EDIT:
As far as I know it gets to the php server side properly.
PHP:
public function submit()
{
$output_status = 'Notice';
$output_title = 'Not Processed';
$output_message = 'The request was unprocessed!';
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|strtolower');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember Me', 'trim|xss_clean|integer');
if ($this->form_validation->run() == TRUE)
{
}
else
{
$output_status = 'Error';
$output_title = 'Form Not Validated';
$output_message = validation_errors();
}
echo json_encode(array('output_status' => $output_status, 'output_title' => $output_title, 'output_message' => $output_message));
}
EDIT 2:
Based off of Sheikh answer. I am getting a response back that says "Unable to access an error message corresponding to your field name." It does say Form Not Validated for the title so the message isn't working.
public function check_username($str)
{
if (preg_match('#[0-9]#', $str) && preg_match('#[a-z]#', $str))
{
return TRUE;
}
$this->form_validation->set_message('username', 'This is not have an accepted value!');
return FALSE;
}
EDIT 3:
What I'm wanting to do is have it report back that there there are validation errors but not the specific errors in the pnotify response. However I do want it to display the specific errors under the form elements.
jQuery Code:
http://pastebin.com/1KehMJkh
Login Form:
http://pastebin.com/EfpBfbfN
I think you can use a callback function in your controller
public function check_username($str)
{
if (preg_match('#[a-z0-9]#', $str)) {
return TRUE;
}
$this->form_validation->set_message('check_username', 'This is not have an accepted value!');
return FALSE;
}
Validation rules for username
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username');
You may like this too.

CodeIgniter form validation valid_email not working

I am trying to use CodeIgniter's form validation class. I've used the "valid_email" parameter, as can be seen from the code below, but even when an invalid email address is entered it still passes the validation check. I tested with the string: testing123
public function login()
{
$this->form_validation->set_rules('authEmail', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'trim|required');
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
if($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
} else {
// Begin authentication
}
}
Anyone have any idea what I'm doing wrong or if this is a CodeIgniter issue?
To note, I am setting a flashdata session as opposed to using:
<?php echo validation_errors(); ?>
... this is because I am doing a redirect back to the homepage (which is the login page as it's a private site).
Try this:
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('authEmail', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'Password', 'trim|required');
if($this->form_validation->run() !== false){
//validation passed
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
// Begin authentication
}
else {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
}
}
I'm just learning to use it as well, but don't you need three parameters? This is from their form validation page:
$this->form_validation->set_rules('email', 'Email', 'required');
From http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules
The field name - the exact name you've given the form field.
A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
The validation rules for this form field.

Categories