Articles → PHP CODEIGNITER → Form Validation In Codeigniter

Form Validation In Codeigniter






Steps




  1. Create a textbox and a "submit" button in a view.
  2. Load the "Form" helper in the controller class.
  3. Load the "form_validation" library in the controller class.
  4. Apply form validation rules using "set_rules" method.
  5. Call "run" method to validate data.



View Changes




<body>
	<div id="container">
		<div id="body"></div>
	</div>
	<?php echo form_open(); 
   echo form_input('username', "); 
   echo form_submit('mysubmit', 'Click Me'); 
   echo form close();?>
</body>
</html>



Controller Changes




  1. Load the "Form" helper in controller class.
  2. Load the "form_validation" library in controller class.
  3. Apply form validation rules using "set_rules" method.
  4. Call "run" method to validate data.


public function Index() { 
$this->load->helper('form'); 
$this->load->library('form_validation'); 
$this->load->view('users'); 
$this->form validation->set rules('username', 'Username', 'required'); 
  if ($this->form_validation->run() == FALSE) { 
    echo "Please enter user name";
  } 
  else{ 
    echo "Valid user name";
  }
}





Output




Picture showing the view when page gets loaded

Click to Enlarge





Picture showing the validation message when page is submitted with empty textbox

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, August 5, 2020

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250