How to do form validation in codeigniter
Form validation in CodeIgniter using its form validation library
Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:- A form is displayed.
- You fill it in and submit it.
- If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.
- This process continues until you have submitted a valid form.
- A View file containing a form.
- A View file containing a "success" message to be displayed upon successful submission.
- A controller function to receive and process the submitted data.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class form_validation extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->helper('form'); } function index() { $this->load->view('form_validation'); } function check_validation() { $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]'); $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean'); if($this->form_validation->run()==true){ print_r($this->input->post()); }else{ $this->load->view('form_validation'); } } }Now lets create view file form_validation.php.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Form Validation In CodeIgniter</title> <style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } h1{ text-align: center; } </style> </head> <body> <div class="warpper"> <h1>Form Validation In CodeIgniter</h1> <?php echo form_open('form_validation/check_validation');?> <table border=1 cellpadding=5 cellspaceing=5> <tr> <td>Name</td> <td> <?php echo form_input('name');?> <?php echo form_error('name'); ?> </td> </tr> <tr> <td>Email Id</td> <td> <?php echo form_input('email');?> <?php echo form_error('email'); ?> </td> </tr> <tr><td>Password</td> <td> <?php echo form_password('password');?> <?php echo form_error('password'); ?> </td> </tr> <tr><td>Confrim password</td> <td> <?php echo form_password('cpassword');?> <?php echo form_error('cpassword'); ?> </td> </tr> <tr><td>website url</td> <td> <?php echo form_input('website_url');?> <?php echo form_error('website_url'); ?> </td> </tr> <tr colspan="2"><td><input type="submit"/></td></tr> </table> <?php echo form_close();?> </div> </body> </html>
Explanation
The form (form_validation.php) is a standard web form with a couple exceptions:
- It uses a form helper to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change.
- Controller has one function: construct() This function initializes the validation class and loads the form helper and load the form_validation library.
- Index(): This function loads view file.
- Run this code in using http://localhost/ci/form_validation/. You will get below screen.
- Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you'll see your success page.
- Form submitted on the check_validation function this function check various validation rules.If validation is true then i will print all post data else it will return to form will error massage.
Set Validation rules:
CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() function:
$this->form_validation->set_rules();
The above function takes three parameters as input:
- 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.
- The validation rules for this form field.
Some validation rules are here.
- trim : This remove space from string both side(left and right).
- required : Fields are compulsory.
- min_length : Minimum length of the field is 5 character.
- xss_clean : This removes malicious data.
- valid_email : This will check user enter valid email or not.
- matches : This will match one value to anotoher.
It's not look well so let's do some css to validation error.Modify check_validation function
function check_validation() { $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]'); $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // added new line if($this->form_validation->run()==true){ print_r($this->input->post()); }else{ $this->load->view('form_validation'); } }
Modify view file also add some css to file
<style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } h1{ text-align: center; } .error{ color: red; } </style>
After that if you submit the form then you will get screen like this screenshot.
Now its look little bit nice.If you inspect element those error then you get <div> with class error.
Changing the Error Delimiters: By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either change these delimiters globally or individually.
- Changing delimiters Globally
To globally change the error delimiters, in your controller function, just after loading the Form Validation class, add this:
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
In this example, we've switched to using div tags. - Changing delimiters Individually
If you want to change error delimiter individually then you do this in view file when you write your form_error().
<?php echo form_error('field name', '<div class="error">', '</div>'); ?>
or
from_error is used to show error individually.If you want to show all error at one place then you can use validation_errors().<?php echo validation_errors('<div class="error">', '</div>'); ?>
If you want to use validation_errors() then you have to change your view file like this.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Form Validation In CodeIgniter</title> <style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } h1{ text-align: center; } .error{ color: red; } </style> </head> <body> <div class="warpper"> <h1>Form Validation In CodeIgniter</h1> <?php echo form_open('form_validation/check_validation');?> <table border=1 cellpadding=5 cellspaceing=5> <tr> <td></td> <td> <?php echo validation_errors(); ?> </td> </tr> <tr> <td>Name</td> <td> <?php echo form_input('name');?> </td> </tr> <tr> <td>Email Id</td> <td> <?php echo form_input('email');?> </td> </tr> <tr><td>Password</td> <td> <?php echo form_password('password');?> </td> </tr> <tr><td>Confrim password</td> <td> <?php echo form_password('cpassword');?> </td> </tr> <tr><td>website url</td> <td> <?php echo form_input('website_url');?> </td> </tr> <tr colspan="2"><td><input type="submit"/></td></tr> </table> <?php echo form_close();?> </div> </body> </html>
After changing the view file if you submit form then it's show error like below image.
And submit form then it will accept all value and it's shows output like this :
but if you check that website url is wrong but it's accepted that value then how to handle this type of situation.No worries to handle this type of situation codeigniter introduce it's callback method.
Callbacks: Your own Validation Functions
The validation system supports callbacks to your own validation functions. This permits you to extend the validation class to meet your needs. For example, here we need to handle website url.so we modify the check_validation function.
function check_validation() { $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]'); $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean'); $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean|callback_checkwebsiteurl'); //modify this line $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); if($this->form_validation->run()==true){ echo "<pre>"; print_r($this->input->post()); }else{ $this->load->view('form_validation'); } }Add new function in your controller file i.e form_validation.php
function checkwebsiteurl($string_url) { $reg_exp = "@^(http\:\/\/|https\:\/\/)?([a-z0-9][a-z0-9\-]*\.)+[a-z0-9][a-z0-9\-]*$@i"; if(preg_match($reg_exp, $string_url) == TRUE){ return TRUE; } else{ $this->form_validation->set_message('checkwebsiteurl', 'URL is invalid format'); return FALSE; } }
Reload your form and submit it with url mohit jain.You can see that the form field data was passed to your callback function for you to process.
To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix. If you need to receive an extra parameter in your callback function, just add it normally after the function name between square brackets, as in: "callback_foo[bar]", then it will be passed as the second argument of your callback function.
Note: You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.
Setting Error Messages
All of the native error messages are located in the following language file: language/english/form_validation_lang.php.
To set your own custom message you can either edit that file, or use the following function:
$this->form_validation->set_message('rule', 'Error Message');
Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.
If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.
In the "callback" example above, the error message was set by passing the name of the function:
$this->form_validation->set_message('checkwebsiteurl', 'URL is invalid format');
Re-populating the form
Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions that permit you to do this.We need to change our view file to implement this function
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Form Validation In CodeIgniter</title> <style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } h1{ text-align: center; } .error{ color: red; } </style> </head> <body> <div class="warpper"> <h1>Form Validation In CodeIgniter</h1> <?php echo form_open('form_validation/check_validation');?> <table border=1 cellpadding=5 cellspaceing=5> <tr> <td>Name</td> <td> <?php echo form_input('name',set_value('name'));?> <?php echo form_error('name'); ?> </td> </tr> <tr> <td>Email Id</td> <td> <?php echo form_input('email',set_value('email'));?> <?php echo form_error('email'); ?> </td> </tr> <tr><td>Password</td> <td> <?php echo form_password('password',set_value('password'));?> <?php echo form_error('password'); ?> </td> </tr> <tr><td>Confrim password</td> <td> <?php echo form_password('cpassword',set_value('cpassword'));?> <?php echo form_error('cpassword'); ?> </td> </tr> <tr><td>website url</td> <td> <?php echo form_input('website_url',set_value('website_url'));?> <?php echo form_error('website_url'); ?> </td> </tr> <tr colspan="2"><td><input type="submit"/></td></tr> </table> <?php echo form_close();?> </div> </body> </html>
Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated.
We use set_value('field name') to re-populating the form.If we enter only website url wrong and submit then its look like this screenshot.All value are automatically re-populating the form.
Helpful links
Codelgniter install Step By Step Tutorial for beginners.
Send E-mail using codeIgniter.
Remove Index.php From CodeIgniter.
Send E-mail using codeIgniter.
Remove Index.php From CodeIgniter.
Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .
How to set cookie in codeigniter
Cookies in codeigniter
To use cookies in codeigniter we have to use its helper class.The Cookie Helper file contains functions that assist in working with cookies.
Below is the example to set cookies in get its values.So we create controller cookies_demo.php.Add the some method like the below example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class cookies_demo extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('cookie'); } // to set cookies function set() { $cookie= array( 'name' => 'demo', 'value' => 'Hello i m cookies which saved in this broswer', 'expire' => '86500', ); $this->input->set_cookie($cookie); echo "cookies successfully set"; } // to get cookies function get() { echo $this->input->cookie('demo',true); } }
Loading this Helper
This helper is loaded using the following code:
$this->load->helper('cookie');
The following functions are available:
$this->input->set_cookie()
Sets a cookie containing the values you specify. There are two ways to pass information to this function so that a cookie can be set: Array Method, and Discrete Parameters:
Array Method
Using this method, an associative array is passed to the first parameter:
$cookie = array( 'name' => 'demo', 'value' => 'Hello i m cookies which saved in this broswer', 'expire' => '86500', 'domain' => '.only4ututorials.blogspot.com', 'path' => '/', 'prefix' => 'myprefix_', 'secure' => TRUE ); $this->input->set_cookie($cookie);
Notes:
- Only the name and value are required. To delete a cookie set it with the expiration blank.
- The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only last as long as the browser is open.
- For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period, like this: .your-domain.com
- The path is usually not needed since the function sets a root path.
- The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.
- The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE.
- If you set 'secure' => TRUE. which is only for https.
- Always try to set 'expire' => 'something'.
Discrete Parameters
If you prefer, you can set the cookie by passing data using individual parameters:
$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
$this->input->cookie()
Lets you fetch a cookie. The first parameter will contain the name of the cookie you are looking for (including any prefixes):
$this->input->cookie('demo',true);
The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist. The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;
Helpful links
Codelgniter install Step By Step Tutorial for beginners.
Send E-mail using codeIgniter.
Remove Index.php From CodeIgniter.
Send E-mail using codeIgniter.
Remove Index.php From CodeIgniter.
Pagination With Codeigniter.
Send mail using codeIgniter and smtp.
Form validation in CodeIgniter with callback function.
Send mail using codeIgniter and smtp.
Form validation in CodeIgniter with callback function.
Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .
CodeIgniter From Scratch : Select records from database
Select records from database for CodeIgniter CRUD
In previous tutorials we learn how to set up out project directory for codeigniter crud.In this we learn how to fetch data from database using MVC of codegniter.
Let's go to our controller i.e. data.php and add some stuff to make CRUD work. Add the some method like the below example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class data extends CI_Controller { function __construct() { parent::__construct(); //load the model $this->load->model('mdl_data'); } // load the view and fetch data from out model function public function index() { $arrData['users'] = $this->mdl_data->getall(); //call the mdl_data getall function to getall data $this->load->view('show',$arrData); // pass all data to view } }
Now let's create out model file which place inside application/model/ name as mdl_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Mdl_data extends CI_Model { function __construct() { parent::__construct(); } function getall(){ $query =$this->db->get('users'); //users is the table name if($query->num_rows()>0){ return $query->result_array(); // this will return all data into array } } }Now let's create our view The results that we have seen we can use them to have Codeigniter CRUD. We just need a view to do it. So a view will look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CRUD In CodeIgniter</title> <style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } .warpper p{ margin: 50px auto; } h1{ text-align: center; } </style> </head> <body> <div class="warpper"> <h1>CRUD In CI</h1> <?php if($this->session->flashdata('success')){ ?> <p style="color:green"><?php echo $this->session->flashdata('success'); ?></p> <?php } ?> <table border=1 cellpadding=5 cellspaceing=5> <tr colspan="6"><td><a href="<?php echo base_url()."data/add/"; ?>">Add New Record</a></td></tr> <tr> <th>Id</th> <th>Name</th> <th>Email Id</th> <th>Edit</th> <th>Delete</th> </tr> <?php if($users) { foreach ($users as $user) { ?> <tr> <td><?php echo $user['id']; ?></td> <td><?php echo $user['name']; ?></td> <td><?php echo $user['email_id']; ?></td> <th><a href="<?php echo base_url()."data/edit/".$user['id']; ?>">Edit</a></th> <th><a href="<?php echo base_url()."data/delete/".$user['id']; ?>">Delete</a></th> </tr> <?php } } ?> </table> </div> </body> </html>
After doing all this run the code like this http://localhost/crud/data/.So a it will look like this:
CodeIgniter From Scratch : Directory Setup for CRUD
Directory Setup And Database Setup For CodeIgniter CRUD.
Step 1: Download Codeigniter and check this Link to set up codeigniter
After Proper Setup Your Page get look like this as seen below
Step 2: Now we are ready to configure our database for our codeigniter project.To do that goto your codeigniter /appication/config/database.php.Open that file in your editor it will look like this.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Active Record class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | NOTE: For MySQL and MySQLi databases, this setting is only used | as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 | (and in table creation queries made with DB Forge). | There is an incompatibility in PHP with mysql_real_escape_string() which | can make your site vulnerable to SQL injection if you are using a | multi-byte character set and are running versions lower than these. | Sites using Latin-1 or UTF-8 database character set and collation are unaffected. | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['autoinit'] Whether or not to automatically initialize the database. | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $active_record variables lets you determine whether or not to load | the active record class */ $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = ''; $db['default']['password'] = ''; $db['default']['database'] = ''; $db['default']['dbdriver'] = 'mysql'; $db['default']['dbprefix'] = ''; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = TRUE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8'; $db['default']['dbcollat'] = 'utf8_general_ci'; $db['default']['swap_pre'] = ''; $db['default']['autoinit'] = TRUE; $db['default']['stricton'] = FALSE; /* End of file database.php */ /* Location: ./application/config/database.php */
you have change some filed i.e
$db['default']['hostname'] = 'localhost'; // change it with your host name $db['default']['username'] = 'root'; // change it with your username $db['default']['password'] = 'root'; // change it with your password $db['default']['database'] = 'crud_database'; // change it with your DB name $db['default']['dbdriver'] = 'mysql';
After that goto your mysql server phpmyadmin create a new database using this query
Create Database crud_database; // change it with your database name
Create your table in your database. Let's say we have the table with table name users. The SQL code that you can insert is:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `email_id` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email_id`) VALUES (1, 'mohit jain', 'mohitj475@gmai.com');Let's go to the next step.
Step 3: Setup directory for the our CodeIgniter CRUD.
Step 4: Open the autoload.php file i.e. in application/config/autoload.php.
/* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in the system/libraries folder | or in your application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'session', 'xmlrpc'); */ $autoload['libraries'] = array('database','session'); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url');
Autoload the our libraries and helper which we use in this Codeigniter crud.
Powered by Blogger.