codeigniter form validation not functioning - php

i am working on a small form that summits data to a table on to a database nothing spectacular. i am trying to add some validation rules but they are not working i am still a beginner at php and codeigniter so cant figure out why can someone look at my code and help me out tnx in advance.
view
<html>
<head>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('http://localhost/Surva/index.php/info/credentials/'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
controller
<?php
class Info extends CI_Controller{
function index(){
$this->load->view('info_view');
}
function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
function validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->from_validation->set_rules('second_name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE){
$this->load->view('info_view');
}else{
redirect('survaycontroller/index');
}
}
}
?>
i used the codeigniter user guide for validation in there explanation it looked very easy the whole structure is taken from the guide i daunt understand what the problem is .

You can do it Simple with one controller. I test it and it works!
Class name test.php
Controller name index
function index(){
$this->load->library('form_validation');
$data['name'] = $this->input->post('name');
$data['second_name'] = $this->input->post('second_name');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('second_name', 'Second Name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()){
$this->info_model->add_record($data);
}
}
$this->load->view('test');
}
View: test.php
<html>
<head>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('test/index'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>

You're not sending the form to the method validation
view
<html>
<head>
</head>
<body>
<?php echo validation_errors();
//you must redirect the form to the right method, in this case your method is "validation" on the controller is "info"
//another thing, you don't need to put all the url, just put the controller and the method, this way when you migrate your website to a server you don't have to worry changing the url
echo form_open('info/validation'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
controller
<?php
class Info extends CI_Controller{
//I've added the public before function
public function index(){
$this->load->view('info_view');
}
//In this one I've added private, Why? Because you don't peopple to use this method if they go to http://(yourdomain). This way you can only use this function inside this controller
private function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
//this one is also as public, and it's the one who we'll receive the post request from your form
public function validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->from_validation->set_rules('second_name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE){
$this->load->view('info_view');
}else{
//if the form is valid then you call the private function credentials and save the data to your database
$this->credentials();
redirect('survaycontroller/index');
}
}
}
?>
Check the alterations I made to your code, if you need some more explain or help you're welcome

second param missing in second rule
$this->from_validation->set_rules('second_name', 'Second Name', 'required|alpha|xss_clean');

Look at the example below, You have to check $this->form_validation->run() inside your credentials() function.
public function add_category()
{
$this->load->library('form_validation');
$data = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required');;
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('position', 'Position', 'trim|numeric');
$artist_category = $this->input->post('artist_category', TRUE);
$data['artist_category'] = $artist_category;
if($this->form_validation->run() === FALSE)
{
$this->template->write('title', 'Category : Add Category');
$this->template->write_view('content', 'category/add_category',$data);
$this->template->render();
}
else
{
$name = trim($this->input->post('name',TRUE));
$description = trim($this->input->post('description',TRUE));
$position = trim($this->input->post('position',TRUE));
$colour = trim($this->input->post('colour',TRUE));
$language_id = trim($this->input->post('language_id',TRUE));
//Add record to categories table
$category_id = $this->Category_model->insert_category($name,$description,$position,$colour,$date_added);
$this->session->set_flashdata('success_msg', 'Category added successfully.');
//Redirect to manage categories
redirect('category');
}
}
else
{
$this->template->write('title', 'Category : Add Category');
$this->template->write_view('content', 'category/add_category');
$this->template->render();
}
}

Related

How to call javascript function in callback function of codeigniter controller?

I want call the javascript function into callback function of codeigniter controller.
Controller: Callback function
public function email_exist($id) {
$this->db->where('email', $id);
$query = $this->db->get('login');
if (!$query->num_rows() > 0) {
$this->form_validation->set_message(__FUNCTION__, $this->email_validate());
return FALSE;
} else {
return TRUE;
}
Javascript: Alert function
function email_validate(){
alert('Invalid Email Id');
}
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Login::email_validate()
Filename: C:\wamp64\www\CodeIgniterProject1\application\controllers\login.php
Line Number: 46
login_form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart(); ?>
<form name="form">
<div class="loginform">
<?php echo form_label('LOGIN', 'login'); ?>
</div>
<div class="email">
<?php echo form_input('email', 'E-MAIL', set_value('email')); ?>
</div>
<div class="password">
<?php echo form_password('password', 'PASSWORD', set_value('password')); ?>
</div>
<div class='checkbox'>
<?php
echo form_checkbox(array(
'name' => 'remember',
'id' => 'remember',
'value' => 'REMEMBER ME',
'checked' => FALSE,
'style' => 'margin:1px'
)) . form_label('REMEMBER ME', 'remember');
?>
</div>
<div class='btnlogin'>
<?php echo form_submit('login', 'LOGIN'); ?>
</div>
</form>
you cant do that in Codeigniter, use Codeigniter default form validation library
View here
if you want to add css for validation errors then try set_error_delimeters()
if you have bootstrap then use
alert alert-danger
class, else create one class
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
see
[other suggestions]
instead of putting all error in the top, you can also try
<?php
echo form_error('email');
form_input('email', 'E-MAIL', set_value('email'));
?>
other options is jquery validation or js validation, write js in view or external .js file
<?php
data = array(
'name' => 'username',
'id' => 'username', //use the id for jquery validation $('#username').on('blur', function() { });
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
'onBlur' => 'email_validate();' //use this for javascript validation
);
echo form_input($data);
?>
im unable to comment, thats why posting as answer

Display data from database using codeigniter

Hi im new to codeigniter and i stuck in displaying data from database. I have tried to find solution but yet can't understand them properly. So can anyone help me with this? really need your expert suggestions thankyou!!
View file Userinsert_view.php
<html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
</head>
<body>
<div id="container">
<?php echo form_open('Userinsert_controller'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1><hr/>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<?php echo form_label('Student Name :'); ?> <?php echo form_error('dname'); ?><br />
<?php echo form_input(array('id' => 'dname', 'name' => 'dname')); ?><br />
<?php echo form_label('Student Email :'); ?> <?php echo form_error('demail'); ?><br />
<?php echo form_input(array('id' => 'demail', 'name' => 'demail')); ?><br />
<?php echo form_label('Student Mobile No. :'); ?> <?php echo form_error('dmobile'); ?><br />
<?php echo form_input(array('id' => 'dmobile', 'name' => 'dmobile', 'placeholder' => '10 Digit Mobile No.')); ?><br />
<?php echo form_label('Student Address :'); ?> <?php echo form_error('daddress'); ?><br />
<?php echo form_input(array('id' => 'daddress', 'name' => 'daddress')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
</body>
</html>
Controller file
Userinsert_controller.php
<?php
class Userinsert_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Userinsert_model');
}
function index() {
//Including validation library
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('dname', 'Username', 'required|min_length[5]|max_length[15]');
//Validating Email Field
$this->form_validation->set_rules('demail', 'Email', 'required|valid_email');
//Validating Mobile no. Field
$this->form_validation->set_rules('dmobile', 'Mobile No.', 'required|regex_match[/^[0-9]{10}$/]');
//Validating Address Field
$this->form_validation->set_rules('daddress', 'Address', 'required|min_length[10]|max_length[50]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Userinsert_view');
} else {
//Setting values for tabel columns
$data = array(
'Student_Name' => $this->input->post('dname'),
'Student_Email' => $this->input->post('demail'),
'Student_Mobile' => $this->input->post('dmobile'),
'Student_Address' => $this->input->post('daddress')
);
//Transfering data to Model
$this->Userinsert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('Userinsert_view', $data);
}
}
Model file
Userinsert_model.php
<?php
class Userinsert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(students) of Database(college)
$this->db->insert('students', $data);
}
}
?>
in controller function
public function GetAll(){
$data['all_data'] = $this->Userinsert_model->selectAllData();
$this->load->view('view_page', $data);
}
in model
public function selectAllData() {
$query = $this->db->get('students');
return $query->result();
}
in view
<?php
foreach ($all_data as $show):
?>
<tr>
<td><?php echo $show->your_table_column_name?></td>
</tr>
<?php
endforeach;
?>
i have read your question you didn't write write the code for fetching data. you only submitted it in you database.
here is simple example so you can easily finds out the solution
in your controller file:
public function view()
{
$this->load->model('uModel'); //edit it with you model name
$data['users']= $this->uModel->All();
$this->load->view('list' , $data);
}
in your model file:
//Func for getting all data of a table in a 'users' variable by using get method
public function All()
{
return $users = $this->db->get('users')->result_array();
}
and create a table view file in view folder where you can fetch your data
<tbody>
<?php if (!empty($users)) { foreach ($users as $user) { ?>
<tr>
<td> <?php echo $user['userid'] ?></td>
<td> <?php echo $user['name'] ?></td>
</tr>
<?php } }
?>
Hope it will help you

Codeigniter form validation does not show error and redirects to blank page

Given below is controller and view but its not validated and only redirects to about:blank page.
I Have made some changes but nothing happens.
controller:
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library(array('form_validation','session')); // load form lidation libaray & session library
$this->load->helper(array('url','html','form')); // load url,html,form helpers optional
}
public function index(){
// set validation rules
$this->form_validation->set_rules('name', 'Name', 'required|min_length[4]|max_length[10]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('number', 'Phone Number', 'required|numeric|max_length[15]');
$this->form_validation->set_rules('subject', 'Subject', 'required|max_length[10]|alpha');
$this->form_validation->set_rules('message', 'Message', 'required|min_length[12]|max_length[100]');
// hold error messages in div
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// check for validation
if ($this->form_validation->run() == FALSE) {
$this->load->view('viewform');
}else{
$this->session->set_flashdata('item', 'form submitted successfully');
redirect('Home');
}
}
}
?>
view:
<?php if(validation_errors()) { ?>
<div class="alert alert-warning">
<?php echo validation_errors(); ?>
</div>
<?php } ?>
<?php if($this->session->flashdata('item')) { ?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('item'); ?>
</div>
<?php } ?>
<?php echo form_open(); ?>
<div class="form-group">
<?php echo form_label('Your Name','name'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "name", "placeholder"=>"Enter Name","value" => set_value('name'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Email address','EmailAddress'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "email", "placeholder"=>"Enter email","value" => set_value('email'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Phone Number','number'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "number", "placeholder"=>"Enter Phone Number","value" => set_value('number'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Subject','subject'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "subject", "placeholder"=>"Enter Subject","value" => set_value('subject'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Message','message'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "message", "placeholder"=>"Enter Message","value" => set_value('message'))); ?>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<?php echo form_close(); ?>
so when any error is there the page is redirected to about:blank even if all fields are proper or improper how to fix this?

Codeigniter form_validation not working

I have used codeigniter in the past but I am building a social network and I am working on the registration. I have autoloaded the form and form validation helpers. I have a form going to my user controller/register function and I have validation rules setup but its ignoring them and proceeding to the next page. I cant for the life of me figure out why. Any help is appreciated..the code and rules are not complete (obviously) but the validation should work at this point
VIEW
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open('user/register/1'); ?>
<?php echo form_hidden('register_id', $randomcode); ?>
<?php echo form_label('First Name', 'first_name'); ?>
<?php echo form_input('first_name',set_value('first_name')); ?>
<br />
<?php echo form_label('Last Name', 'last_name'); ?>
<?php echo form_input('last_name',set_value('last_name')); ?>
<br />
<?php echo form_label('Gender', 'gender:'); ?>
<?php echo form_radio('gender', 'male'); ?> Male
<?php echo form_radio('gender', 'female'); ?> Female
<br />
<?php echo form_label('Date of Birth:', 'birthdate'); ?>
<?php echo form_date('birthdate'); ?>
<br />
<?php echo form_label('Zipcode:', 'zipcode'); ?>
<?php echo form_input('zipcode',set_value('zipcode')); ?>
<br />
<?php echo form_label('Email:', 'email'); ?>
<?php echo form_email('email',set_value('email')); ?>
<br />
<?php echo form_label('Password', 'password'); ?>
<?php echo form_password('password'); ?>
<br />
<?php echo form_label('Confirm', 'password2'); ?>
<?php echo form_password('password2'); ?>
<br />
<?php
$data = array(
'name' => 'submit',
'class' => 'big-blue-btn',
'value' => 'Sign Up'
);
?>
<?php echo form_submit($data); ?>
<?php echo form_close(); ?>
CONTROLLER
public function register($step){
if($step == 1){
$this->form_validation->set_rules('first_name', 'first_name', 'required');
$this->form_validation->set_rules('last_name', 'last_name', 'required');
if($this->form_validation->run() == FALSE){
//Views
$data['main_content'] = 'public/user/register1';
$this->load->view('public/template', $data);
} else {
//Post values to array
$data = array(
'register_id' => $this->input->post('register_id'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'zipcode' => $this->input->post('zipcode'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'password2' => $this->input->post('password2')
);
//Send input to model
$this->User_model->register1($data);
$data['show_sidebar'] = FALSE;
}
} elseif($step == 2){
//Send input to model
$this->User_model->register2($data);
} elseif($step == 3){
//Send input to model
$this->User_model->register3($data);
}
}
Review your code, you're missing a closing bracket on your first if.

Form validation stops working when I render pages using another controller

I wrote a quick CI library class to render my pages so I wouldn't have to keep typing '$this->load->view' all the time and for DRY. Now when I re-render my contact form after passing in invalid data the error messages aren't showing up.
The library class:
class Page extends CI_Controller {
public function render($page, $data) { // $page should be path to page view
$this->load->view('fragments/header', $data);
$this->load->view('fragments/navigation');
$this->load->view($page);
$this->load->view('fragments/navigation');
$this->load->view('fragments/footer');
}
}
and the controller:
class Contact extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->library(array('form_validation', 'email', 'page'));
}
public function index() {
$this->form_validation->set_rules('sender_name', 'From', 'required');
$this->form_validation->set_rules('sender_email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->library('page');
$this->page->render('contact/contact', array('title' => 'Contact Me')); // pass in page title
/* IT WORKED THIS WAY
$this->load->view('fragments/header', array('title' => 'Contact Me')); // pass in page title
$this->load->view('fragments/navigation');
$this->load->view('contact/contact'); // TODO maintain form state
$this->load->view('fragments/navigation');
$this->load->view('fragments/footer');
*
*/
}
//SNIP
contact form view:
<h1>Contact Me</h1>
<?php echo form_open('contact', 'id="contact_form"'); ?>
<label for="sender_name">Name:</label>
<?php echo form_input('sender_name'); ?>
<span class="error"><?php echo form_error('sender_name'); ?></span>
<label for="sender_email">Email:</label>
<?php echo form_input('sender_email'); ?>
<span class="error"><?php echo form_error('sender_email'); ?></span>
<label for="subject">Subject:</label>
<?php echo form_input('subject'); ?>
<span class="error"><?php echo form_error('subject'); ?></span>
<label for="message">Message:</label>
<?php echo form_textarea('message'); ?>
<span class="error"><?php echo form_error('message'); ?></span>
<?php echo form_submit('submit', 'Send'); ?>
How can I render pages using this helper and still retrieve error messages from form_validation library?
Create a view called template.php in your views folder with the following code in it:
<?php
$this->load->view('fragments/header', $this->_ci_cached_vars); // pass $data vars
$this->load->view('fragments/navigation');
$this->load->view($view);
$this->load->view('fragments/navigation');
$this->load->view('fragments/footer');
Then use the below controller code:
public function index() {
$this->form_validation->set_rules('sender_name', 'From', 'required');
$this->form_validation->set_rules('sender_email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() === FALSE) {
$data = array(
'view' => 'contact/contact',
'title' => 'Contact Me');
$this->load->view('template', $data);
}
You don't need to create a library to do this as you can just create a template view which will load the appropriate views and the specified view and pass the data along to them.

Categories