CodeIgniter form validation valid_email not working - php

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.

Related

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 access an error message corresponding to your field name in CI3

I have checked all the possible things that might go wrong with my code but still it showing me this error. Please help .
Unable to access an error message corresponding to your field name Username.(check_username)
And this is my code below:
public function index()
{
if ( ! file_exists(APPPATH.'/views/login.php'))
{
/* Whoops, we don't have a page for that! */
show_404();
}
$this->load->helper('security');
$this->load->library('form_validation'); // Including Validation Library.
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // Displaying Errors in Div
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username'); // Validation for Username Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); // Validation for Password field.
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
}
function check_username($username)
{
if ($username == 'test') {
$this->form_validation->set_message('check_username','already exists.');
return false;
} else {
return TRUE;
}
}
}
Do $config['global_xss_filtering'] = TRUE; in config file.
in Codeigniter-3 xss_filtering is not a part of form_validation.
You have to add the validation language in the system folder. Check the video
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&sqi=2&ved=0ahUKEwi71dGkn73MAhVBQI4KHeZJC2gQtwIIPTAF&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D56EDSocDhjk&usg=AFQjCNE_nhBpNwUOz9nkrcRYYgL50p34Kw&sig2=PSUISbtldDaWWdTyKJ6CPw&bvm=bv.121070826,d.c2E

Codeigniter Form Validation in Model

Hello all, this is my first CI project.
I have a simple form validation function in my model.
function verify_login()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
var_dump($this->form_validation->run());
die;
if ($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->load->view('login_view');
} else {
//Go to private area
redirect('home', 'refresh');
}
}
This only works when it's in a controller but not in a model. When I try passing the variables from the controller to the function in the model, the variables get received but won't process.
Can someone enlighten me? Thank you.
its fine to do your form validation in a model. But you want to have the validation return True or False to your controller. Not call a view. So like
// in your Model lets call it Users
function verify_login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run() == FALSE) {
return FALSE ;
} else {
return TRUE;
}
}
// Your callback function
// in Controller
function verify(){
if( $this->users->verify_login() == FALSE ){
// $this->errormessage will be available in any view that is called from this controller
$this-errormessage = "There was an error with your Log In. Please try again." ;
$this->showLogin() ; }
else {
// set a session so you can confirm they are logged in on other pages
$this->setLoginSession($this->input->post('username', TRUE)) ;
$this->showUserHome(); }
}
Another thing to think about -- often people know their user name but mess up their password. So if you check for them separately you can adjust the error message accordingly. And if you check for user name and there are no results -- you don't need to check for password and in the error message you can tell them there is no user by that name.
My biggest recommendation to you is to not do validations like this in your model. If you're validating in your model it needs to be against a database value directly and not a form.
Please let me know if that solves your problem, if not please comment and I'll edit my answer.
UPDATE: Please ignore some of the above, as I was going off theory and not fact :)
I'll have to dig deeper into the CI core to get a good idea of what's wrong with this. Your code itself looks ok. Only thing I can see is that your callback may not exist in your model and only in your controller. Echoing the below I do not consider this a good use of the model.
The docs on validations
class Data_model extends CI_Model
{
public function rules()
{
return [
['field' => 'pertanyaan',
'label' => 'pertanyaan',
'rules' => 'required|is_unique[data.pertanyaan]'],
['field' => 'jawaban',
'label' => 'jawaban',
'rules' => 'required']
];
}
}
class Datas extends CI_Controller
{
public function add()
{
$data = $this->data_model;
$validation = $this->form_validation;
$validation->set_rules($data->rules());
if ($validation->run()) {
$data->save();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$this->load->view("admin/data/new_form");
}
}

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 Callback checking multiple fields

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; ?>

Categories