How to display the error on each fields in codeigniter - php

$this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
$this->form_validation->set_rules('user_password', 'Password', 'required|matches[confirm_password]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required');
$this->form_validation->set_rules('cname', 'College Name', 'required');
$this->form_validation->set_rules('dob', 'Date of Birth', 'required|callback_valid_date');
$this->form_validation->set_rules('addr', 'Address', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required|min_length[10]|max_length[10]');
$this->form_validation->set_rules('education', 'Education', 'required');
$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('result', validation_errors());
redirect('login/register');
}
else
{
$rr = $this->user->register_user();
$this->session->set_flashdata('result', $rr);
redirect('login/register');
}
}
basically using $this->session->flashdata("result"); to show the result but i want each filed seprately validate i have tried form_error("field name "); but it's not working displaying empty result

Instead of redirecting, try to load the same form if there are any validation errors.
In your controller page.
function your_function(){
// load form helper
$this->load->helper(array('form', 'url'));
// load form validation library
$this->load->library('form_validation');
// validation rules
$this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
// check form for validations
if ($this->form_validation->run() == FALSE){
// load the same form/view
$this->load->view('myform');
} else{
// redirect to success page
}
}
In view page: can use the form_error() function to show an error message next to each form field
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<?php echo form_error('fname'); ?>
<input type="text" name="fname" value="<?php echo set_value('fname'); ?>" size="50" />

Related

Codeigniter validation errors are not displaying

My codeigniter validation errors are not displaying someone can help?
my code is
public function addProduct(){
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
if (!$this->form_validation->run() == FALSE)
{
// some stuff on validation success
}
else{
$this->load->view('product/addProduct');
}
}
and i have added
echo validation_errors(); in my view and action of the form is product/addProduct.
Try this it's work for you.
form_error() function return your form error.
$post_fields = $this->input->post();
$data['msg'] = '<ul>';
foreach ($post_fields as $k => $v) {
if (form_error($k))
$data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
}
$data['msg'].='</ul>';
$this->load->view('product/addProduct',$data);
OR
echo validation_errors();//this function also return form error.
On view example
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<!-- lower case for the controller name on form open -->
<?php echo form_open_multipart('product/addProduct');?>
<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />
<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close();?>
Controller
Make sure your file name and class name is something like this below where first letter only upper case
Guide
Filename: Product.php
<?php
class Product extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->helper('url');
}
public function addProduct(){
// You can get data from here also
$this->data['some'] = 'Blah';
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
// remove your !
if ($this->form_validation->run() == FALSE){
// You can just display view in this area you do not have to load it multiple times
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
} else {
// some stuff on validation success
}
}
}
Also check you have set your base url in config.php is required now in CI3 versions.

Codeigniter- How to preserve form values if error on submit

I have the form field like
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php if($user->postal_code === NULL) { echo set_value('postal_code');} else { echo $user->postal_code;} ?>">
<label for="form_control_1">Postal Code</label>
<span class="help-block">Postal Code is required</span>
and my function is
public function postProfile() {
if ($_POST) {
$this->form_validation->set_rules('postal_code', 'Postal Code', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('month', 'Month', 'required');
$this->form_validation->set_rules('day', 'Day', 'required');
$this->form_validation->set_rules('year', 'Year', 'required');
$this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required');
if ($this->form_validation->run() === FALSE) {
//$this->session->set_flashdata('err', validation_errors());
$this->session->set_flashdata('email_err', form_error('email'));
$this->session->set_flashdata('postal_code_err', form_error('postal_code'));
$this->session->set_flashdata('gender_err', form_error('gender'));
$this->session->set_flashdata('country_err', form_error('country'));
$this->session->set_flashdata('day_err', form_error('day'));
$this->session->set_flashdata('year_err', form_error('year'));
$this->session->set_flashdata('month_err', form_error('month'));
$this->session->set_flashdata('mobile_err', form_error('mobile_number'));
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
$dob = $this->input->post('month') . '/' . $this->input->post('day') . '/' . $this->input->post('year');
$userData = array(
'email' => $this->input->post('email'),
'date_of_birth' => $dob,
'gender' => $this->input->post('gender'),
'country' => $this->input->post('country'),
'mobile_number' => $this->input->post('mobile_number'),
'postal_code' => $this->input->post('postal_code'),
);
$updateUser = $this->user->updateUser($this->session->userdata['front']['id'], $userData);
if ($updateUser) {
$this->session->set_flashdata('err', '<div class="alert alert-success">Profile Updated Successfuly</div>');
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
echo "Un expected error ";
exit;
}
}
} else {
$this->logout();
}
}
but value is not shown for the postal code field in case of validation errors
When error occur then you need to render view instead of rediect().
if ($this->form_validation->run() == FALSE) {
// no need to set_flashdata here for form_error()
$this->load->view('view_form',$data);
return;
}else{
//success code
}
Now view file
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php echo set_value('postal_code');?>">
<?php echo form_error('postal_code','<p class="alert alert-danger">','</p>');?>
Now your form will repopulate previous data if any error occur. In the same time you will see error message under your postal_code field
You can set these values in flashdata and redirect to your form. For example
if ($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors(),
'name' => $this->input->post('name')//check this
);
$this->session->set_flashdata($data);
redirect('YOUR-URL-HERE');
}
And in your form use value attribute of form input as given below
<input type="text" class="form-control" name="name" placeholder="Name" value="<?= $this->session->flashdata('name'); ?>">

Codelgniter Form Validation Showed double repeated form after validate

Tried to read though all the webpages and docs in google and stack flow but still could not solve the problem.
I tried to do a simple data validation for registration form and it turns out showing another form below the original one after I press submit to show the error messages with a new form.
I am a newbie in this language so please let me know if I attache not enough codes or information.
Controller account:
<?php
class Account extends MY_Controller {
public function __construct() {
parent::__construct();
session_start();
$this->load->model('user');
$this->load->helper(array('form','url','html'));
$this->load->library('session');
$this->load->library('form_validation');
}
public function registration() {
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if($this->input->post('submit')) {
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if ($this->form_validation->run() == FALSE){
$this->load->view('account/registration',$data); ←---------------- (I think this is wrong, it makes load the second form out.)
}
else{
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0,
);
$this->user->create_user($data);
redirect('/account/login');
}
}
}
}
View Registration.php
<center>
<?php echo form_open_multipart('account/registration'); ?>
<h5><?php echo $b_username;?> (Minimum 5 characters)</h5>
<input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" size="50" /><?php echo form_error('username'); ?>
<h5><?php echo $b_email;?></h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<?php echo form_error('email'); ?>
<h5><?php echo $b_password;?> (Minimum 5 characters)</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<?php echo form_error('password'); ?>
<h5><?php echo $b_passconf;?></h5>
<input type="text" name="passconf" value="" size="50" />
<?php echo form_error('passconf'); ?>
<h5></h5>
<div><?php echo form_submit('submit', 'Submit') ?></div>
</center>
Model user.php
<?php
class User extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function users_info() {
$data['b_id'] = 'id';
$data['b_username'] = 'Username';
$data['b_email'] = 'Email';
$data['b_password'] = 'Password';
$data['b_passconf'] = 'Enter Password Again';
$data['b_is_admin'] = 'Is_admin';
$data['b_default_privacy'] = 'Default_privacy';
$data['b_first_name'] = 'First_Name';
$data['b_last_name'] = 'Last_Name';
$data['b_gender'] = 'Gender';
$data['b_birthday'] = 'Birthday';
$data['b_friend_id'] = 'Friend_id';
$data['b_weight'] = 'Weight';
$data['b_height'] = 'Height';
$data['b_daily_cal_intake'] = 'Daily_calorie_intake';
$data['b_target_weight'] = 'Target_weight';
$data['b_regional_id'] = 'Region';
$data['b_profile_pic'] = 'Profile Picture';
return $data;
}
function retrieve_by_username($username) {
$query = $this->db->get_where('001_users',array('username'=>$username));
return $query->row_array();
}
function retrieve_by_email($email) {
$query = $this->db->get_where('001_users', array('email'=>$email));
return $query->row_array();
}
Change your function to this and try..
public function registration()
{
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if ($this->form_validation->run() == false) // if validation fails for first time and every time when ever condtion is not satisified
{
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
}
else
{
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0
);
$this->user->create_user($data);
// send sucess msg here
redirect('/account/login');
}
}
}

Codeigniter validation is not working

I am new in codeigniter .I have done validation for my project .But it is not working fine .I have written my all code here .First is view page and second is my controller page.Please help anyone
<?php $this->load->helper('form');
echo validation_errors();
echo form_open('SM_in_controller/sm_login_action');
?>
<input class="login_input" type="text" placeholder="Username" name="username" id="username"/>
<input type="submit" value="Login" class="login_button" id="login_button"/>
</form>
and my controller
public function sm_login_action() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
}
In your controller, when you call the "run" method is when the proccess is done:
public function sm_login_action() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
if( $this->form_validation->run() ) { // Return TRUE on success
// Success
} else {
// Failure
}
}
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
try this for more details.
https://www.codeigniter.com/user_guide/libraries/form_validation.html
Try this
<input class="login_input" type="text" placeholder="Username" name="username" id="username" required/>
Hope this helps

how to validate form in a order codeigniter

I would like to validate my login form like Google does.
First check username then check password; If both are empty then there is only an error on the username box.
In CodeInginter, if both are empty it prints each field is required messages.
Can we mimic this functionality easily with CodeIgnightor?
you need to research before you post some question. These kind of information available in codeIgniter user guide. Any way i am providing simple example.
View file: login.php
<form action="<?php echo ROOT_FOLDER ?>/controller_name/post_login" method="post" >
<p>
<label>Email:</label> <?php echo form_error('email'); ?><br />
<input type="text" class="text" name="email" value="<?php echo set_value('email'); ?>" />
</p>
<p>
<label>Password:</label> <?php echo form_error('passwd'); ?><br />
<input type="password" name="passwd" class="text" value="" />
</p>
<p>
<input type="submit" class="submit" value="Login" />
</p>
</form>
Controller function which is written in controller file..........
public function post_login()
{
$error_in_validation=set_form_validation($this->config->item('login_form'));
if($error_in_validation){
show_form_validation_error('controller_file_name/login');
}
else
{
$email=$this->input->post('email');
$passwd=$this->input->post('passwd');
$ret=$this->model_file_name->user_login($email, $passwd);
if($ret == NULL){
$model=array();
$model['error_msg']=$this->config->item('login_form_error_code_1');;
$this->load->view('controller_file_name/login',$model);
} else {
redirect("ro_manager/home");
}
}
}
After this you need to create you need to create a file name called form_validation in config folder. In that you need to write the validation rules as per user guide.
$config['login_form'] = array (
array
(
'key' => 'email',
'value' => 'Email',
'rule' => 'trim|required|valid_email|xss_clean'
),
array
(
'key' => 'passwd',
'value' => 'Password',
'rule' => 'trim|required|alpha_numeric|xss_clean'
)
);
Try like this way
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('myform');
}else{
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('myform');
}
$this->load->view('formsuccess');
}

Categories