This is for multiple forms with validation on codeigniter

center

Hi there everyone, this is my second tutorial on code igniter. Here, I will discuss about using multiple forms with validation.

Here is the procedure:

First we need to create a form to your views, here is one example.

Views:

<p><?php echo $this->validation->error_string; ?></p>
<form id="form1" method="post" action="validateform">
  <fieldset>
      <legend>Login</legend>
      <p>
        <h3>Username</h3>
        <input name="username1" type="text" id="username1" />
      </p>
      <p>
        <h3>Password</h3>
        <input name="password1" type="password" id="password1" />
      </p>
      <p>
        <input name="form1" type="submit" id="form1" value="Envoyer" />
      </p>
  </fieldset>
</form>
<form id="form2" method="post" action="validateform">
<fieldset>
<legend>Subscribe</legend>
<h5>Username</h5>
<input type="text" name="username2" id="username2" />
<p>
<h5>Password</h5>
  <input type="password" name="password2" id="password2" />
</p>
<p>
<h5>Password Confirm</h5>
  <input type="password" name="passwordCheck" id="passwordCheck" />
</p>
<p>
  <input name="form2" type="submit" id="form2" value="Envoyer" />
</p>
</fieldset>
</form>

 

This is the view that I’ve created it has two forms then create id which define to post to your controller. Your Form must have this “ echo $this->validation->error_string; ” to print out our error messages.

 

Next, lets create a simple controller called “Validateform” in our system/application/controllers directory.
Controllers:

<?php
class Validateform extends Controller {

  function index() {

    $this->load->library('validation');

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

    if (!$this->validation->run()) {
      $this->load->view('view.php');
    }
    else {
      if ($this->input->post('form1'))
          echo 'Form 1 posted !';
      else if ($this->input->post('form2'))
          echo 'Form 2 posted !';
    }
  }
}
?>

 

Rule Reference
The following is a list of all the rules that are available to use:

 

Hope these codes will help all of you.
Thank you, and have a nice day.

  • Share/Bookmark



Post a Comment

You must be logged in to post a comment.