blob: 8c033ee504432b87a4a4f7f7f915494f0f32c1a5 [file] [log] [blame]
adminb0dd10f2006-08-25 17:25:49 +00001<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html>
3<head>
4
5<title>Code Igniter User Guide</title>
6
7<style type='text/css' media='all'>@import url('../userguide.css');</style>
8<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
9
admin17a890d2006-09-27 20:42:42 +000010<script type="text/javascript" src="../nav/nav.js"></script>
admin2296fc32006-09-27 21:07:02 +000011<script type="text/javascript" src="../nav/prototype.lite.js"></script>
admin17a890d2006-09-27 20:42:42 +000012<script type="text/javascript" src="../nav/moo.fx.js"></script>
adminb0dd10f2006-08-25 17:25:49 +000013<script type="text/javascript">
14window.onload = function() {
15 myHeight = new fx.Height('nav', {duration: 400});
16 myHeight.hide();
17}
18</script>
19
20<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
21<meta http-equiv='expires' content='-1' />
22<meta http-equiv= 'pragma' content='no-cache' />
23<meta name='robots' content='all' />
24<meta name='author' content='Rick Ellis' />
25<meta name='description' content='Code Igniter User Guide' />
26
27</head>
28<body>
29
30<!-- START NAVIGATION -->
31<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
32<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle.jpg" width="153" height="44" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
33<div id="masthead">
34<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
35<tr>
admin41a16852006-09-26 18:17:19 +000036<td><h1>Code Igniter User Guide Version 1.5.0</h1></td>
adminb0dd10f2006-08-25 17:25:49 +000037<td id="breadcrumb_right"><a href="../toc.html">Full Table of Contents</a></td>
38</tr>
39</table>
40</div>
41<!-- END NAVIGATION -->
42
43
44<!-- START BREADCRUMB -->
45<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
46<tr>
47<td id="breadcrumb">
48<a href="http://www.codeigniter.com/">Code Igniter Home</a> &nbsp;&#8250;&nbsp;
49<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
50Form Validation
51</td>
52<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="www.codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td>
53</tr>
54</table>
55<!-- END BREADCRUMB -->
56
57<br clear="all" />
58
59
60<!-- START CONTENT -->
61<div id="content">
62
63<h1>Form Validation</h1>
64
65<p>Before explaining Code Igniter's approach to data validation, let's describe the ideal scenario:</p>
66
67<ol>
68<li>A form is displayed.</li>
69<li>You fill it in and submit it.</li>
70<li>If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.</li>
71<li>This process continues until you have submitted a valid form.</li>
72</ol>
73
74<p>On the receiving end, the script must:</p>
75
76<ol>
77<li>Check for required data.</li>
78<li>Verify that the data is of the correct type, and meets the correct criteria. (For example, if a username is submitted
79it must be validated to contain only permitted characters. It must be of a minimum length,
80and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.)
81<li>Sanitize the data for security.</li>
82<li>Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)</li>
83<li>Prep the data for insertion in the database.</li>
84</ol>
85
86
87<p>Although there is nothing complex about the above process, it usually requires a significant
88amount of code, and to display error messages, various control structures are usually placed within the form HTML.
89Form validation, while simple to create, is generally very messy and tedious to implement.</p>
90
91<dfn>Code Igniter provides a comprehensive validation framework that truly minimizes the amount of code you'll write.
92It also removes all control structures from your form HTML, permitting it to be clean and free of code.</dfn>
93
94<h2>Overview</h2>
95
96<p>In order to implement Code Igniter's form validation you'll need three things:</p>
97
98<ol>
99<li>A <a href="../general/views.html">View</a> file containing the form.</li>
100<li>A View file containing a "success" message to be displayed upon successful submission.</li>
101<li>A <a href="../general/controllers.html">controller</a> function to receive and process the submitted data.</li>
102</ol>
103
104<p>Let's create those three things, using a member sign-up form as the example.</p>
105
106<h2>The Form</h2>
107
108<p>Using a text editor, create a form called <dfn>myform.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp>
109folder:</p>
110
111
112<textarea class="textarea" style="width:100%" cols="50" rows="30"><html>
113<head>
114<title>My Form</title>
115</head>
116<body>
117
118<?=$this->validation->error_string; ?>
119
120<?=form_open('form'); ?>
121
122<h5>Username</h5>
123<input type="text" name="username" value="" size="50" />
124
125<h5>Password</h5>
126<input type="text" name="password" value="" size="50" />
127
128<h5>Password Confirm</h5>
129<input type="text" name="passconf" value="" size="50" />
130
131<h5>Email Address</h5>
132<input type="text" name="email" value="" size="50" />
133
134<div><input type="submit" value="Submit" /></div>
135
136</form>
137
138</body>
139</html></textarea>
140
141
142<h2>The Success Page</h2>
143
144
145<p>Using a text editor, create a form called <dfn>formsuccess.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp>
146folder:</p>
147
148
149<textarea class="textarea" style="width:100%" cols="50" rows="14"><html>
150<head>
151<title>My Form</title>
152</head>
153<body>
154
155<h3>Your form was successfully submitted!</h3>
156
157<p><?=anchor('form', 'Try it again!'); ?></p>
158
159</body>
160</html></textarea>
161
162
163<h2>The Controller</h2>
164
165<p>Using a text editor, create a controller called <dfn>form.php</dfn>. In it, place this code and save it to your <samp>applications/controllers/</samp>
166folder:</p>
167
168
169<textarea class="textarea" style="width:100%" cols="50" rows="21"><?php
170
171class Form extends Controller {
172
173 function index()
174 {
175 $this->load->helper(array('form', 'url'));
176
177 $this->load->library('validation');
178
179 if ($this->validation->run() == FALSE)
180 {
181 $this->load->view('myform');
182 }
183 else
184 {
185 $this->load->view('formsuccess');
186 }
187 }
188}
189?></textarea>
190
191
192<h2>Try it!</h2>
193
194<p>To try your form, visit your site using a URL similar to this one:</p>
195
196<code>www.your-site.com/index.php/<var>form</var>/</code>
197
198<p><strong>If you submit the form you should simply see the form reload. That's because you haven't set up any validation
199rules yet, which we'll get to in a moment.</strong></p>
200
201
202<h2>Explanation</h2>
203
204<p>You'll notice several things about the above pages:</p>
205
206<p>The <dfn>form</dfn> (myform.php) is a standard web form with a couple exceptions:</p>
207
208<ol>
209<li>It uses a <dfn>form helper</dfn> to create the form opening.
210Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper
211is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable
212and flexible in the event your URLs change.</li>
213
214<li>At the top of the form you'll notice the following variable:
215<code>&lt;?=$this->validation->error_string; ?&gt;</code>
216
217<p>This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.</p>
218</li>
219</ol>
220
221<p>The <dfn>controller</dfn> (form.php) has one function: <dfn>index()</dfn>. This function initializes the validation class and
222loads the <var>form helper</var> and <var>URL helper</var> used by your view files. It also <samp>runs</samp>
223the validation routine. Based on
224whether the validation was successful it either presents the form or the success page.</p>
225
226<p><strong>Since you haven't told the validation class to validate anything yet, it returns "false" (boolean false) by default. The <samp>run()</samp>
227function only returns "true" if it has successfully applied your rules without any of them failing.</strong></p>
228
229
230<h2>Setting Validation Rules</h2>
231
232<p>Code Igniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data
233at the same time. Let's see it in action, we'll explain it afterwards.</p>
234
235<p>In your <dfn>controller</dfn> (form.php), add this code just below the validation initialization function:</p>
236
237<code>$rules['username'] = "required";<br />
238$rules['password'] = "required";<br />
239$rules['passconf'] = "required";<br />
240$rules['email'] = "required";<br />
241<br />
242$this->validation->set_rules($rules);</code>
243
244<p>Your controller should now look like this:</p>
245
246<textarea class="textarea" style="width:100%" cols="50" rows="28"><?php
247
248class Form extends Controller {
249
250 function index()
251 {
252 $this->load->helper(array('form', 'url'));
253
254 $this->load->library('validation');
255
256 $rules['username'] = "required";
257 $rules['password'] = "required";
258 $rules['passconf'] = "required";
259 $rules['email'] = "required";
260
261 $this->validation->set_rules($rules);
262
263 if ($this->validation->run() == FALSE)
264 {
265 $this->load->view('myform');
266 }
267 else
268 {
269 $this->load->view('formsuccess');
270 }
271 }
272}
273?></textarea>
274
275<p><dfn>Now submit the form with the fields blank and you should see the error message.
276If you submit the form with all the fields populated you'll see your success page.</dfn></p>
277
278<p class="important"><strong>Note:</strong> The form fields are not yet being re-populated with the data when
279there is an error. We'll get to that shortly, once we're through explaining the validation rules.</p>
280
281
282<h2>Changing the Error Delimiters</h2>
283
284<p>By default, the system adds a paragraph tag (&lt;p&gt;) around each error message shown. You can easily change these delimiters with
285this code, placed in your controller:</p>
286
287<code>$this->validation->set_error_delimiters('<kbd>&lt;div class="error"></kbd>', '<kbd>&lt;/div></kbd>');</code>
288
289<p>In this example, we've switched to using div tags.</p>
290
291<h2>Cascading Rules</h2>
292
293<p>Code Igniter lets you pipe multiple rules together. Let's try it. Change your rules array like this:</p>
294
295
296<code>$rules['username'] = "required|min_length[5]|max_length[12]";<br />
297$rules['password'] = "required|matches[passconf]";<br />
298$rules['passconf'] = "required";<br />
299$rules['email'] = "required|valid_email";</code>
300
301<p>The above code requires that:</p>
302
303<ol>
304<li>The username field be no shorter than 5 characters and no longer than 12.</li>
305<li>The password field must match the password confirmation field.</li>
306<li>The email field must contain a valid email address.</li>
307</ol>
308
309<p>Give it a try!</p>
310
311<p class="important"><strong>Note:</strong> There are numerous rules available which you can read about in the validation reference.</p>
312
313
314<h2>Prepping Data</h2>
315
316<p>In addition to the validation functions like the ones we used above, you can also prep your data in various ways.
317For example, you can set up rules like this:
318
319<code>$rules['username'] = "<kbd>trim</kbd>|required|min_length[5]|max_length[12]|<kbd>xss_clean</kbd>";<br />
320$rules['password'] = "<kbd>trim</kbd>|required|matches[passconf]|<kbd>md5</kbd>";<br />
321$rules['passconf'] = "<kbd>trim</kbd>|required";<br />
322$rules['email'] = "<kbd>trim</kbd>|required|valid_email";</code>
323
324<p>In the above, we are "trimming" the fields, converting the password to MD5, and running the username through
325the "xss_clean" function, which removes malicious data.</p>
326
327<p class="important"><strong>Any native PHP function that accepts one parameter can be used as a rule, like <dfn>htmlspecialchars</dfn>,
328<dfn>trim</dfn>, <dfn>MD5</dfn>, etc.</strong></p>
329
330<p><strong>Note:</strong> You will generally want to use the prepping functions <strong>after</strong>
331the validation rules so if there is an error, the original data will be shown in the form.</p>
332
333<h2>Callbacks: Your own Validation Functions</h2>
334
335<p>The validation system supports callbacks to your own validation functions. This permits you to extend the validation class
336to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can
337create a callback function that does that. Let's create a simple example.</p>
338
339<p>In your controller, change the "username" rule to this:</p>
340
341<code>$rules['username'] = "callback_username_check"; </code>
342
343<p>Then add a new function called <dfn>username_check</dfn> to your controller. Here's how your controller should look:</p>
344
345
346<textarea class="textarea" style="width:100%" cols="50" rows="44"><?php
347
348class Form extends Controller {
349
350 function index()
351 {
352 $this->load->helper(array('form', 'url'));
353
354 $this->load->library('validation');
355
356 $rules['username'] = "callback_username_check";
357 $rules['password'] = "required";
358 $rules['passconf'] = "required";
359 $rules['email'] = "required";
360
361 $this->validation->set_rules($rules);
362
363 if ($this->validation->run() == FALSE)
364 {
365 $this->load->view('myform');
366 }
367 else
368 {
369 $this->load->view('formsuccess');
370 }
371 }
372
373 function username_check($str)
374 {
375 if ($str == 'test')
376 {
377 $this->validation->set_message('username_check', 'The %s field can not be the word "test"');
378 return FALSE;
379 }
380 else
381 {
382 return TRUE;
383 }
384 }
385
386}
387?></textarea>
388
389<p>Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your
390callback function for you to process.</p>
391
392<p><strong>To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix.</strong></p>
393
394<p>The error message was set using the <dfn>$this->validation->set_message</dfn> function.
395Just remember that the message key (the first parameter) must match your function name.</p>
396
397<p class="important"><strong>Note:</strong> You can apply your own custom error messages to any rule, just by setting the
398message similarly. For example, to change the message for the "required" rule you will do this:</p>
399
400<code>$this->validation->set_message('required', 'Your custom message here');</code>
401
402<h2>Re-populating the form</h2>
403
404<p>Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data.
405This is done similarly to your rules. Add the following code to your controller, just below your rules:</p>
406
407<code>$fields['username'] = 'Username';<br />
408$fields['password'] = 'Password';<br />
409$fields['passconf'] = 'Password Confirmation';<br />
410$fields['email'] = 'Email Address';<br />
411<br />
412$this->validation->set_fields($fields);</code>
413
414<p>The array keys are the actual names of the form fields, the value represents the full name that you want shown in the
415error message.</p>
416
417<p>The index function of your controller should now look like this:</p>
418
419
420<textarea class="textarea" style="width:100%" cols="50" rows="30">function index()
421{
422 $this->load->helper(array('form', 'url'));
423
424 $this->load->library('validation');
425
426 $rules['username'] = "required";
427 $rules['password'] = "required";
428 $rules['passconf'] = "required";
429 $rules['email'] = "required";
430
431 $this->validation->set_rules($rules);
432
433 $fields['username'] = 'Username';
434 $fields['password'] = 'Password';
435 $fields['passconf'] = 'Password Confirmation';
436 $fields['email'] = 'Email Address';
437
438 $this->validation->set_fields($fields);
439
440 if ($this->validation->run() == FALSE)
441 {
442 $this->load->view('myform');
443 }
444 else
445 {
446 $this->load->view('formsuccess');
447 }
448}</textarea>
449
450
451<p>Now open your <dfn>myform.php</dfn> view file and update the value in each field so that it has an object corresponding to its name:</p>
452
453
454<textarea class="textarea" style="width:100%" cols="50" rows="30"><html>
455<head>
456<title>My Form</title>
457</head>
458<body>
459
460<?=$this->validation->error_string; ?>
461
462<?=form_open('form'); ?>
463
464<h5>Username</h5>
465<input type="text" name="username" value="<?=$this->validation->username;?>" size="50" />
466
467<h5>Password</h5>
468<input type="text" name="password" value="<?=$this->validation->password;?>" size="50" />
469
470<h5>Password Confirm</h5>
471<input type="text" name="passconf" value="<?=$this->validation->passconf;?>" size="50" />
472
473<h5>Email Address</h5>
474<input type="text" name="email" value="<?=$this->validation->email;?>" size="50" />
475
476<div><input type="submit" value="Submit" /></div>
477
478</form>
479
480</body>
481</html></textarea>
482
483
484<p>Now reload your page and submit the form so that it triggers an error. Your form fields should be populated
485and the error messages will contain a more relevant field name.</p>
486
487
488
489<h2>Showing Errors Individually</h2>
490
491<p>If you prefer to show an error message next to each form field, rather than as a list, you can change your form so that it looks like this:</p>
492
493
494<textarea class="textarea" style="width:100%" cols="50" rows="20">
495<h5>Username</h5>
496<?=$this->validation->username_error; ?>
497<input type="text" name="username" value="<?=$this->validation->username;?>" size="50" />
498
499<h5>Password</h5>
500<?=$this->validation->password_error; ?>
501<input type="text" name="password" value="<?=$this->validation->password;?>" size="50" />
502
503<h5>Password Confirm</h5>
504<?=$this->validation->passconf_error; ?>
505<input type="text" name="passconf" value="<?=$this->validation->passconf;?>" size="50" />
506
507<h5>Email Address</h5>
508<?=$this->validation->email_error; ?>
509<input type="text" name="email" value="<?=$this->validation->email;?>" size="50" /></textarea>
510
511<p>If there are no errors, nothing will be shown. If there is an error, the message will appear, wrapped in the delimiters you
512have set (&lt;p> tags by default).</p>
513
514<p class="important"><strong>Note: </strong>To display errors this way you must remember to set your fields using the <kbd>$this->validation->set_fields</kbd>
515function described earlier. The errors will be turned into variables that have "_error" after your field name.
516For example, your "username" error will be available at:<br /><dfn>$this->validation->username_error</dfn>.</p>
517
518
519<h2>Rule Reference</h2>
520
521<p>The following is a list of all the native rules that are available to use:</p>
522
523
524
525<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
526<tr>
527<th>Rule</th>
528<th>Parameter</th>
529<th>Description</th>
530<th>Example</th>
531</tr><tr>
532
533<td class="td"><strong>required</strong></td>
534<td class="td">No</td>
535<td class="td">Returns FALSE if the form element is empty.</td>
536<td class="td">&nbsp;</td>
537</tr><tr>
538
539<td class="td"><strong>matches</strong></td>
540<td class="td">Yes</td>
541<td class="td">Returns FALSE if the form element does not match the one in the parameter.</td>
542<td class="td">matches[form_item]</td>
543</tr><tr>
544
545<td class="td"><strong>min_length</strong></td>
546<td class="td">Yes</td>
547<td class="td">Returns FALSE if the form element is shorter then the parameter value.</td>
548<td class="td">min_length[6]</td>
549</tr><tr>
550
551<td class="td"><strong>max_length</strong></td>
552<td class="td">Yes</td>
553<td class="td">Returns FALSE if the form element is longer then the parameter value.</td>
554<td class="td">max_length[12]</td>
555</tr><tr>
556
557<td class="td"><strong>exact_length</strong></td>
558<td class="td">Yes</td>
559<td class="td">Returns FALSE if the form element is not exactly the parameter value.</td>
560<td class="td">exact_length[8]</td>
561</tr><tr>
562
563<td class="td"><strong>alpha</strong></td>
564<td class="td">No</td>
565<td class="td">Returns FALSE if the form element contains anything other than alphabetical characters.</td>
566<td class="td">&nbsp;</td>
567</tr><tr>
568
569<td class="td"><strong>alpha_numeric</strong></td>
570<td class="td">No</td>
571<td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters.</td>
572<td class="td">&nbsp;</td>
573</tr><tr>
574
575<td class="td"><strong>alpha_dash</strong></td>
576<td class="td">No</td>
577<td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.</td>
578<td class="td">&nbsp;</td>
579</tr><tr>
580
581<td class="td"><strong>numeric</strong></td>
582<td class="td">No</td>
583<td class="td">Returns FALSE if the form element contains anything other than numeric characters.</td>
584<td class="td">&nbsp;</td>
585</tr><tr>
586
587<td class="td"><strong>valid_email</strong></td>
588<td class="td">No</td>
589<td class="td">Returns FALSE if the form element does not contain a valid email address.</td>
590<td class="td">&nbsp;</td>
591</tr>
592
593</table>
594
595<p><strong>Note:</strong> These rules can also be called as discreet functions. For example:</p>
596
597<code>$this->validation->required($string);</code>
598
599<p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter.</p>
600
601
602
603<h2>Prepping Reference</h2>
604
605<p>The following is a list of all the prepping functions that are available to use:</p>
606
607
608
609<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
610<tr>
611<th>Name</th>
612<th>Parameter</th>
613<th>Description</th>
614</tr><tr>
615
616<td class="td"><strong>xss_clean</strong></td>
617<td class="td">No</td>
618<td class="td">Runs the data through the XSS filtering function, described in the <a href="input.html">Input Class</a> page.</td>
619</tr><tr>
620
621<td class="td"><strong>prep_for_form</strong></td>
622<td class="td">No</td>
623<td class="td">Converts special characters so that HTML data can be shown in a form field without breaking it.</td>
624</tr><tr>
625
626<td class="td"><strong>prep_url</strong></td>
627<td class="td">No</td>
628<td class="td">Adds "http://" to URLs if missing.</td>
629</tr><tr>
630
631<td class="td"><strong>strip_image_tags</strong></td>
632<td class="td">No</td>
633<td class="td">Strips the HTML from image tags leaving the raw URL.</td>
634</tr><tr>
635
636<td class="td"><strong>encode_php_tags</strong></td>
637<td class="td">No</td>
638<td class="td">Converts PHP tags to entities.</td>
639</tr>
640
641</table>
642
643<p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter,
644like <kbd>trim</kbd>, <kbd>htmlspecialchars</kbd>, <kbd>urldecode</kbd>, etc.</p>
645
646
647<h2>Setting Custom Error Messages</h2>
648
649<p>All of the native error messages are located in the following language file: <dfn>language/english/validation_lang.php</dfn></p>
650
651<p>To set your own custom message you can either edit that file, or use the following function:</p>
652
653<code>$this->validation->set_message('<var>rule</var>', '<var>Error Message</var>');</code>
654
655<p>Where <var>rule</var> corresponds to the name of a particular rule, and <var>Error Message</var> is the text you would like displayed.</p>
656
657
658</div>
659<!-- END CONTENT -->
660
661
662<div id="footer">
663<p>
664Previous Topic:&nbsp;&nbsp;<a href="uri.html">URI Class</a>
665&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
666<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
667<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
668Next Topic:&nbsp;&nbsp;<a href="xmlrpc.html">XML-RPC Class</a>
669<p>
670<p><a href="http://www.codeigniter.com">Code Igniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 &nbsp;&middot;&nbsp; <a href="http://www.pmachine.com">pMachine, Inc.</a></p>
671</div>
672
673</body>
674</html>