Codeigniter - My form validation callback doesn't work - php

I have tried to copy from Codegniter's documentation, but I can't make form validation callbacks working.
I added helper form, url and library form_validation. It's not working and always returns "false"
Controller
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
}
$this->template
->build('myform',array());
}
public function username_check($str)
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
View
<form method="post" action="" class="form-horizontal form-label-left">
<div class="col-xs-12 col-md-9">
<div class="x_panel">
<div class="form-group col-xs-12">
<div class="col-xs-3">
<label class="control-label">Folder name</label>
</div>
<div class="col-xs-9">
<input type="text" name="username" value="" class="form-control " id="" placeholder="">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>

Extend your form_validation library in Libraries.php
MY_Form_validation.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI =& $module;
return parent::run($group);
}
}
/* End of file MY_Form_validation.php */
/* Location: ./application/libraries/MY_Form_validation.php */

My Controller function is like this and it runs perfectly. I have autoloaded all libraries
public function change_password()
{
if($this->isLoggedin()){
$data['title']='Change Password';
if($_POST)
{
$config=array(
array(
'field' => 'old_password',
'label' => 'Old Password',
'rules' => 'trim|required|callback_checkPassword'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false)
{
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$this->load->view('change_password',$data);
}
else
{
// if validation passes, check for user credentials from database
$this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
$this->session->set_flashdata('log_success','Congratulations! Password Changed');
redirect(base_url() . 'Login/dashboard');
}
}
else
{
$this->load->view('change_password',$data);
}
}
else
{
redirect(base_url().'Login');
}
}
public function checkPassword($str)
{
$check=$this->Login_model->checkPassword($str);
if($check)
{
return true;
}
else
{
$this->form_validation->set_message('checkPassword', 'The Current Password you have provided is incorrect');
return false;
}
}

In HTML (Add ID field)
<input type="text" name="username" value="" class="form-control " id="username" placeholder="">
<button type="submit" class="btn btn-success" id="submit">Submit</button>
In your AJAX code
<script type="text/javascript">
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var username= $("#username").username();
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/controller/Method",
data:{ username:username},
success:function(res)
{
}
});
});
});
</script>>
In Controller
No need of check if($_SERVER['REQUEST_METHOD'] == 'POST') because it comes through it always
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
$this->template->build('myform',array());
}
public function username_check($str)
{
if (empty($str))
{
echo "Empty";
}
else
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
}
Check more about CodeIgniter callback function

Related

CodeIgniter Simple Login in Bootstrap Form

I am new to CodeIgniter and trying to sortout a simple login form using the framework.
FORM View
<form action="login" method="post">
<input type="text" class="form-control" placeholder="Username" name="username" value="">
<input type="password" class="form-control" placeholder="Password" name="password" value="">
<div style="color:red;" class="col pl-1">
<?php
echo $error;
?>
</div>
<button type="submit" class="btn btn-block btn-primary" name="signin">Login</button>
</form>
Controller
class Loginauth extends CI_Controller
{
public function index()
{
$this->load->view('auth');
}
public function login()
{
$data=array();
if($this->input->post('signin'))
{
$u=$this->input->post('username');
$p=$this->input->post('password');
if($u=='admin' && $p=='123')
{
redirect('loginauth/dashboard');
}
else
{
$data['error']="<h3 style='color:red'>Invalid login details</h3>";
}
}
$this->load->view('auth',#$data);
}
function dashboard()
{
$this->load->view('success');
}
}
When I submit the login page, it is redirected to
localhost/CodeIgniter-3.1.10/index.php/login
(without username and password), but nothing happens.
Could you please help me to sort this thing?
You should load the form helper and form_validation library first.
public function login()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$data['error'] = validation_errors();
if($this->form_validation->run() === FALSE){
$this->load->view('auth',#$data);
}else{
$u=$this->input->post('username');
$p=$this->input->post('password');
if($u=='admin' && $p=='123')
{
redirect('loginauth/dashboard');
}
else
{
$data['error']="<h3 style='color:red'>Invalid login details</h3>";
$this->load->view('auth',#$data);
}
}
}
your form action should be: action="<?php echo base_url('index.php/loginauth/login') ?>". that's it, let me know the result.

Ajax does not work in codeigniter 3

I want to make registration in CodeIgniter. Everything is fine, however, I want to add Ajax to show error and success messages. However, it does not work. Here is my view:
<div class="modal-body">
<div id="messages"></div>
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input name="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('mail'); ?></span>
<input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('password2'); ?></span>
<input name="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
</div>
Here is my controller:
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url', 'security'));
$this->load->library(array('session', 'form_validation', 'email'));
$this->load->database();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
//set validation rules
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
$this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');
$to_email= $this->input->post('mail');
$data['courses'] = $this->popular_courses_model->get_popular_courses();
$data['news'] = $this->news_model->get_news();
//validate form input
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('templates/header');
$this->load->view('pages/index', $data);
$this->load->view('templates/footer');
}
else
{
//insert the user registration details into database
$data = array(
'instructors_slug' => $this->input->post('username'),
'mail' => $to_email,
'password' => $this->input->post('password')
);
// insert form data into database
if ($this->user_model->insertUser($data)) {
if ($this->user_model->sendEmail($to_email)) {
// successfully sent mail
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user/register');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.$to_email.' gondermir '.$this->email->print_debugger().'</div>');
redirect('user/register');
}
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">daxil elemir</div>');
redirect('user/register');
}
}
}
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
if($this->form_validation->run() === FALSE){
$this->load->view('login/login', $data);
} else {
// Get username
$username = $this->input->post('username');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'instructor_id' => $instructor_id,
'id' => $id,
'instructors_slug' => $username,
'name' => $name,
'logged_in' => true
);
$this->session->set_userdata($user_data);
redirect('');
} else {
$this->session->set_flashdata('login_failed', 'Неверныый логин или пароль');
redirect('');
}
}
}
public function logout() {
$this->session->unset_userdata('logged_in');
$this->session->unset_userdata('instructor_id');
$this->session->unset_userdata('id');
$this->session->unset_userdata('instructors_slug');
$this->session->unset_userdata('name');
redirect('');
}
function verify($hash=NULL)
{
if ($this->user_model->verifyEmailID($hash))
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
redirect('');
}
else
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
redirect('');
}
}
}
?>
and here is my register.js file:
$(document).ready(function() {
$("#registrationform").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
response.messages+
'</div>');
$("#registerForm")[0].reset();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
}
else {
$.each(response.messages, function(index, value) {
var element = $("#"+index);
$(element)
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
$(element).after(value);
});
}
} // /success
}); // /ajax
return false;
});
});
You problem is the dynamic binding issue.
Maybe you are calling the ready function before the JQuery Javascript is included?
Here is your error.
Uncaught ReferenceError: $ is not defined at register.js:
// Remove This.
//$(document).ready(function() {
//$("#registrationform").unbind('submit').bind('submit', function() {
// var form = $(this);
// Add This.
$('#your_model_id').on('click', '.submit_button_class', function(e) {
var str = $( "#registrationform" ).serialize();
And Please You should put the references to the jquery scripts first.
like this.
<script language="JavaScript" type="text/javascript" src="your_script.js"></script>

Callback form validation is not working in HMVC

I have a problem in using my call back for form validation.
The validation should check the tbl_fees_type if there is an existing fees_type_name before creating a new fee type, if it exist already it will show an error The Fees Type already exists.
I know the required form validation is working because it shows it is required but when it comes to callback validation that checks the information from the database if it exists using callback its not working.
This is my code:
So I have a Feestype controller like this
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Feestype extends MX_Controller {
public function __construct() {
parent::__construct();
// loading the fees type model
$this->load->model('model_feestype');
// loading the form validation library
$this->load->library('form_validation');
}
public function index() {
$this->load->view('feestype');
}
public function create()
{
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'fees_type_name',
'label' => 'Fees Type Name',
'rules' => 'trim|required|callback_validate_feestypename'
//this is the callback
),
array(
'field' => 'fees_type_role',
'label' => 'Fees Type Role',
'rules' => 'trim|required|'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$create = $this->model_feestype->create();
if($create === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully added";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
// call back validation function to do
public function validate_feestypename()
{
$validate = $this->model_feestype->validate_feestypename();
if($validate === true) {
$this->form_validation->set_message('validate_feestypename', 'The {field} already exists');
return false;
}
else {
return true;
}
}
}
?>
and this is the model_feestype.php Model
<?php if (!defined ('BASEPATH')) exit ('No direct script access allowed');
class Model_Feestype extends CI_Model {
public function __construct() {
parent:: __construct();
}
public function create()
{
$insert_data = array(
'fees_type_name' => $this->input->post('fees_type_name'),
'fees_type_role' => $this->input->post('fees_type_role')
);
$status = $this->db->insert('tbl_fees_type', $insert_data);
return ($status === true ? true : false);
}
public function validate_feestypename()
{
$feestypeName = $this->input->post('fees_type_name');
$sql = "SELECT * FROM tbl_fees_type WHERE fees_type_name = ?";
$query = $this->db->query($sql, array($feestypeName));
return ($query->num_rows() == 1 ? true : false);
}
}
?>
and this is my modal form view php file.
<div class="modal fade" tabindex="-1" role="dialog" id="addFeetype">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Fees Type</h4>
</div>
<form method="post" action="feestype/create" id="createFeetypeForm">
<div class="modal-body">
<div class="form-group">
<label for="fees_type_name">Fees Type Name</label>
<input type="text" class="form-control" id="fees_type_name" name="fees_type_name" placeholder="Fees Type Name">
</div>
<div class="form-group">
<label for="fees_type_name">Fees Type Role</label>
<select class="form-control" name="fees_type_role" id="fees_type_role">
<option></option>
<option>School Fees</option>
<option>Personal Fees</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The form required validation is working that looks like this.
Form validation required working
this is the sample form that I want to achieve, it has the same source code but it runs in codeigniter (not HMVC) but it's not working in my work (HMVC).
Woking callback validation should look like this
All you need to do to make callbacks work in HMVC is
MY_Form_validation.php
<?php
class MY_Form_validation extends CI_Form_validation {
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
Then in the run part add $this in run($this)
$this->form_validation->run($this)
In the folder libraries create class MY_Form_validation
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation{
function run($module = '', $group = ''){
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
// call back validation function to do
public function validate_feestypename()
{
$this->CI =& get_instance();
$this->CI->load->model('model_feestype');
$validate = $this->CI->model_feestype->validate_feestypename();
if($validate === true) {
$this->CI->form_validation->set_message->set_message('validate_feestypename', 'The {field} already exists');
return false;
}
else {
return true;
}
}
}

Cant return error message in CodeIgniter 3 callback

I have a problem in my code. I am creating a simple login using CI3 for my small project. My problem is I have an error message in callback validation.
Here's the error I received whenever I try to validate my form.
Unable to access an error message corresponding to your field name Password.(check_database)
Here's mo code in controller:
public function index() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
$this->form_validation->set_error_delimiters('<div class="error text-red">', '</div>');
if($this->form_validation->run() == FALSE) {
$data = array();
$data['modules'] = $this->flx_lib->moduler($data);
$this->load->view('login', $data);
} else {
//ok
}
}
public function check_database($password) {
$username = $this->input->post($username);
$result = $this->flx_users->validate_user($username, $password);
if($result) {
//ok
return TRUE;
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
Here's my view:
<div class="form-group has-feedback <?php error_exists('username'); ?>">
<input type="text" class="form-control" name="username" placeholder="Username" />
<span class="fa fa-user form-control-feedback "></span>
<?php echo form_error('username'); ?>
</div>
<div class="form-group has-feedback <?php error_exists('password'); ?>">
<input type="password" class="form-control" name="password" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
<?php echo form_error('password'); ?>
</div>
Can you help me with this? I am using CI3 with HMVC
Ok I found the error in my code. Actually its an issue with HMVC form validation.
Here's the link for the correct answer:
CodeIgniter - Unable to access an error message corresponding to your field name Password.(pword_check)
Solution:
1. Create MY_Form_validation.php file in libraries folder and paste following code in it.
if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function run($module = '', $group = '')
{
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
And change if ($this->form_validation->run() == FALSE) to if ($this->form_validation->run($this) == FALSE) thats all folks..
public function index() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database',
array('check_database' => 'Invalid username or password.')
);
$this->form_validation->set_error_delimiters('<div class="error text-red">', '</div>');
if($this->form_validation->run() == FALSE) {
$data = array();
$data['modules'] = $this->flx_lib->moduler($data);
$this->load->view('login', $data);
} else {
//ok
}
}
public function check_database($password) {
$username = $this->input->post($username);
$result = $this->flx_users->validate_user($username, $password);
if($result) {
//ok
return TRUE;
} else {
return FALSE;
}
}
I recoded this one. Something was mixed up.
This is from docs:
$this->form_validation->set_rules('field_name', 'Field Label', 'rule1|rule2|rule3',
array('rule2' => 'Error Message on rule2 for this field_name')
);

form-validation in codeigniter

<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="password" name="password"/>
<br/>
<input type="submit" value="Login"/>
</form>
I use that code to validate a filled in form but the browser shows nothing after I submit. The URL of my browser is stuck at http://example.com/index.php/verifylogin
verifylogin.php is defined like this
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//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');
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');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
class Auth extends CI_Controller{
public function __construct(){parent::__construct();}
/**
* Login Form
*
* $route['login'] = 'auth/login_form';
*
*/
public function login_form(){
$this->load->view('login_form');
}
/**
* Login Validation
*
* $route['login/check'] = 'auth/login_check';
* Point your form to login/check
*/
public function login_check()
{
if($this->form_validation->run() == TRUE)
{
//form validates...
}else
{
//no redirect! just show for again!
$this->login_form();
}
}
}

Categories