-
Notifications
You must be signed in to change notification settings - Fork 26
Validation and multiple forms
[url]http://www.codeigniter.com/forums/viewthread/48535/[/url]
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 :
[b]The view (view.tpl) :[/b] [code] <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="">
LoginUsername <input name="username1" type="text" id="username1" />
Password <input name="password1" type="password" id="password1" />
<input name="form1" type="submit" id="form1" value="Envoyer" />
</form> <form id="form2" method="post" action=""> Subscribe Username <input type="text" name="username2" id="username2" />Password <input type="password" name="password2" id="password2" />
Confirm Password <input type="password" name="passwordCheck" id="passwordCheck" />
<input name="form2" type="submit" id="form2" value="Envoyer" />
</form><?php echo $this->validation->error_string; ?>
</body> </html>[/code][b]The controller :[/b]
[code]<?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 !';
}
} } ?>[/code]