Skip to content


Subversion checkout URL

You can clone with
Download ZIP

Validation and multiple forms

Derek Jones edited this page · 9 revisions
Clone this wiki locally

Category:Library::Community | Category:Library::Forms | Category:Library::Validation

I've had many difficulties to use the CI Validation class with multiple forms (i.e. a login form and a subscription form within the same page), but I've found a solution... Hope it will help. :coolsmile:

Here how to proceed : Before you define the validation rules, test the posted submit button or other hidden inputs which can define what form has been posted to your controller. Then you can define validation rules depending on each form you can be posted.

Here's an example :

The view (view.tpl) :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
&lt;html xmlns=""&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;

&lt;form id="form1" method="post" action=""&gt;
        <label for="username1">Username</label>
        &lt;input name="username1" type="text" id="username1" /&gt;
        <label for="password1">Password</label>
        &lt;input name="password1" type="password" id="password1" /&gt;
        &lt;input name="form1" type="submit" id="form1" value="Envoyer" /&gt;
&lt;form id="form2" method="post" action=""&gt;<fieldset>
<label for="username2">Username</label>
&lt;input type="text" name="username2" id="username2" /&gt;
  <label for="password2">Password</label>
  &lt;input type="password" name="password2" id="password2" /&gt;
  <label for="passwordCheck">Confirm Password</label>
  &lt;input type="password" name="passwordCheck" id="passwordCheck" /&gt;
  &lt;input name="form2" type="submit" id="form2" value="Envoyer" /&gt;
<p>&lt;?php echo $this->validation->error_string; ?&gt;</p>

The controller :

&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Test extends Controller {

  function index() {


    if ($this->input->post('form1')) {
      $rules['username1'] = 'required|alpha_numeric';
      $rules['password1'] = 'required|alpha_numeric';
    else if ($this->input->post('form2')) {
      $rules['username2'] = 'required|alpha_numeric';
      $rules['password2'] = 'required|matches[password2]';
      $rules['passwordCheck'] = 'required|alpha_numeric';

    if (!$this->validation->run()) {
    else {
      if ($this->input->post('form1'))
          echo 'Form 1 posted !';
      else if ($this->input->post('form2'))
          echo 'Form 2 posted !';
Something went wrong with that request. Please try again.