forked from bcit-ci/CodeIgniter
-
Notifications
You must be signed in to change notification settings - Fork 4
Validation and multiple forms
Derek Jones edited this page Jul 5, 2012
·
9 revisions
Category:Library::Community | Category:Library::Forms | Category:Library::Validation http://www.codeigniter.com/forums/viewthread/48535/
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>
<body>
<form id="form1" method="post" action="">
<fieldset>
<legend>Login</legend>
<p>
<label for="username1">Username</label>
<input name="username1" type="text" id="username1" />
</p>
<p>
<label for="password1">Password</label>
<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=""><fieldset>
<legend>Subscribe</legend>
<label for="username2">Username</label>
<input type="text" name="username2" id="username2" />
<p>
<label for="password2">Password</label>
<input type="password" name="password2" id="password2" />
</p>
<p>
<label for="passwordCheck">Confirm Password</label>
<input type="password" name="passwordCheck" id="passwordCheck" />
</p>
<p>
<input name="form2" type="submit" id="form2" value="Envoyer" />
</p>
</fieldset>
</form>
<p><?php echo $this->validation->error_string; ?></p>
</body>
</html>
The controller :
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test 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.tpl');
}
else {
if ($this->input->post('form1'))
echo 'Form 1 posted !';
else if ($this->input->post('form2'))
echo 'Form 2 posted !';
}
}
}
?>