Form Validation Call Back Function Not Working - php

Here Is My COde I m checking username is already exist or not in datbase
when i validate and submit the form duplicate entry entered in database i want that if already exist it show validation error
My Controller
public function index()
{
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'User Name', 'callback_checkuser');
$this->form_validation->set_rules('role', 'Role', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run()==TRUE)
{
$user['u_name'] = $this->input->post('name');
$user['role'] = $this->input->post('role');
$user['password']= md5($this->input->post('pass'));
$u_id = $this->custom_model->add_user($user);
if($u_id){
$data['msg'] = 'Successfully Created!!!!';
}
}
}
$this->load->template('add_user', $data);
}
function checkuser($name) {
if($this->custom_model->check_name($name) == false) {
false;
}else {
$this->form_validation->set_message('checkuser', 'This user already exist');
return true;
}
}
Here is My Model
public function check_name($name) {
$sql = "SELECT * FROM users WHERE u_name='".$name."' ";
$query = $this->db->query($sql);
$res = $query->row_array();
if (is_array($res) && count($res) > 0){
return $res;
}
return false;
}

There is a return statement missing in the function checkuser, but more importantly, you should invert the value you return. According to the example in the docs, when you set a validation message because of a validation error, you should return false, and return true when the validation passes.
So add a return, and change the boolean values. BTW, you don't really need an else clause and the word "exist" needs an additional "s":
function checkuser($name) {
if ($this->custom_model->check_name($name) == false) {
return true; // the user does not yet exist, so all is OK
}
$this->form_validation->set_message('checkuser', 'This user already exists');
return false; // this is a duplicate user name: not OK
}

Use this:
$this->form_validation->set_rules('name', 'User Name', 'trim|required|is_unique[users.u_name]');// trim and required added too
Docs.

Related

Message: Undefined variable: email under Controllers

I am getting Undefined Variable email under Controllers.
Controller : login.php
public function index() {
$this->load->view('bootstrap/header');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->load->model('Login_db');
$is_exist = $this->Login_db->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message('isEmailExist', 'Email Address Already Exists!');
return FALSE;
} else {
return TRUE;
}
$this->load->view('bootstrap/footer');
}
Model : login_db.php
public function isEmailExist($email) {
$this->db->select('user_id');
$this->db->where('email', $email);
$query = $this->db->get('login');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
I have to check whether email exists are not.
before
$is_exist = $this->Login_db->isEmailExist($email);
add this (in case of a POST request)
$email = $this->input->post('email');
or this ((in case of a GET request)
$email = $this->input->get('email');
by checking your code i came to assume that you want to allow only the emails which is already not in table ? why have not you validated with is_unique like
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[login.email]');
or you can change the line as
$this->Login_db->isEmailExist($this->input->post('email'));
or you should define $email before passing it / calling the function
$email=$this->input->post('email');
for custom massaging :
$this->form_validation->set_rules( 'email', 'Email', 'required|valid_email|is_unique[login.email]', array( 'is_unique' => 'Email already exists' ) );
better you go through the manual
https://www.codeigniter.com/user_guide/libraries/form_validation.html
the var $email used here
$is_exist = $this->Login_db->isEmailExist($email); line 5 of index
is never isntanciate. You should instantiate it to avoir error.

Codeigniter user form errors not showing

On my codeigniter login. If user types in incorrect user name it should display error saying Username or Password Incorrect as flash-data. And if user puts in username that does not exist then would throw error Username Not Match Any Records.
Cannot get the form database check errors to display correct way. I can login OK but just not throwing login flash-data errors correct.
How can I get my form database errors to work correct. The main codeigniter form validation are OK just not throwing my database errors.
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->login();
} else {
if ($this->input->post('username') && $this->input->post('password')) {
// Gets the user information from the database.
$user = $this->user_login_model->get('username', $this->input->post('username'));
if ($user) {
// If User Login Success
if ($this->user_login_model->check_password($this->input->post('password'), $user['password']) == TRUE) {
$this->user->login($user['user_id']);
redirect('admin/dashboard');
} else {
$this->session->set_flashdata('error', 'Username or Password Is Does Not Match Any Records!');
$this->login();
}
}
}
}
}
public function login() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['text_login'] = $this->lang->line('text_login');
$data['text_register'] = $this->lang->line('text_register');
$data['entry_username'] = $this->lang->line('entry_username');
$data['entry_password'] = $this->lang->line('entry_password');
$data['action'] = site_url('admin');
$data['button_login'] = $this->lang->line('button_login');
return $this->load->view('common/login', $data);
}
Get User model
/**
* Retrieve a user
*
* #param string where
* #param int value
* #param string user_identification field
*/
public function get($where, $value = FALSE) {
if (!$value) {
$value = $where;
$where = 'user_id';
}
$user = $this->db->where($where, $value)->get($this->table)->row_array();
return $user;
}
Flashdata will only be shown if the user is redirected to another page.
On the failed login action you only load a view to the user's screen. Try altering
$this->login();
to
redirect('controller/login'); //ofc change the controller name first

Display flashdata message in codeigniter callback function

I've this registration function and the related callback to check if an username already exists in the database. It works all perfectly, but I have problems with flashdata message
Here's the code:
/*
* Checks registration
*/
public function verify(){
$this->form_validation->set_rules('nome', 'Nome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('cognome', 'Cognome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|xss_clean|callback_check_username');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password_conf', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('error_reg', 'Something goes wrong, please check your registration form');
redirect('registration');
}
else
{
$this->registration_m->add_user();
$this->session->set_flashdata('success_reg', 'Registration Successful!');
redirect('registration');
}
}
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
return false;
} else {
return true;
}
}
As you can see there's a redirect on the function verify(), and the flashdata before is correctly shown in case of errors.
My Question is: is there a way to show (in case of error) the flashdata inside the callback function without changing the logic of this piece of code?
Hope I was clear at all, cheers.
Modify your code as below
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');
return false;
} else {
return true;
}
}
See differences in code
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');

Codeigniter : Resetting the form values

In my view, what I want to do is clear the form fields once the user has been successfully registered. Everything works fine here i.e. the user is being registered, success message is being shown to the user except that what I want to do is the clear the values of the form fields, for which I am using this
// Clear the form validation field data, so that it doesn't show up in the forms
$this->form_validation->_field_data = array();
After I added this, CI keeps giving me this error:
Fatal error: Cannot access protected property CI_Form_validation::$_field_data in
C:\wamp\www\CodeIgniter\application\controllers\user.php on line 92
Here is the relevent controller code:
public function signup()
{
// If the user is logged in, don't allow him to view this page.
if (($this->_isLoggedIn()) === true) {
$this->dashboard();
}
else
{
$data['page'] = 'signup';
$data['heading'] = 'Register yourself';
$data['message'] = $this->_regmsg;
$this->load->library('form_validation');
// $this->form_validation->set_rules('is_unique', 'Sorry! This %s has already been taken. Please chose a different one.');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]|callback_valid_username');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
// run will return true if and only if we have applied some rule all the rules and all of them are satisfied
if ($this->form_validation->run() == false) {
$data['errors'] = isset($_POST['submit']) ? true : false;
$data['success'] = false;
$this->_load_signup_page($data);
}
else{
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
// Clear the form validation field data, so that it doesn't show up in the forms
$this->form_validation->_field_data = array();
$this->_load_signup_page($data);
}
}
}
}
private _load_signup_page($data){
$this->load->view('template/main_template_head');
$this->load->view('template/blue_unit', $data);
$this->load->view('signup', $data);
$this->load->view('template/main_template_foot');
}
Can anyone please tell me what's the deal with this line?
$this->form_validation->_field_data = array();
P.S: Here is how I am showing the values in the form:
<?php echo set_value('fieldname'); ?>
It means this is a protected property and you can not use it directly. Instead of this you can do it simply like this
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
unset($_POST)
$this->_load_signup_page($data);
}
This way is not recommended. Instead if you redirect to the same controller the form will reset itself automatically.
if($this->users->register_user($_POST)){
$data['errors'] = false;
$data['success'] = true;
redirect('controllername/signup');
}
Still if you need success messages you can use flash data for this. Here

Codeigniter form validation error message

I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error

Categories