diff options
author | Greg Aker <greg.aker@ellislab.com> | 2010-04-15 01:23:29 +0200 |
---|---|---|
committer | Greg Aker <greg.aker@ellislab.com> | 2010-04-15 01:23:29 +0200 |
commit | b4ae79daccd0823fd86bda446046c933164ffb01 (patch) | |
tree | 4de84f5df30ffca924cd06e35f5f7e57ee7d5440 | |
parent | 676e1cda78b7bc4eede7cad509a8d9f015a51816 (diff) | |
parent | ef88a906ed8b2050f4c6e6d8fbd73cc5b6adc7a3 (diff) |
Automated merge with http://hg.ellislab.com/CodeIgniter2/
-rw-r--r-- | system/libraries/Validation.php | 875 | ||||
-rw-r--r-- | user_guide/changelog.html | 11 | ||||
-rw-r--r-- | user_guide/libraries/validation.html | 740 |
3 files changed, 6 insertions, 1620 deletions
diff --git a/system/libraries/Validation.php b/system/libraries/Validation.php deleted file mode 100644 index a42b7760b..000000000 --- a/system/libraries/Validation.php +++ /dev/null @@ -1,875 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/** - * CodeIgniter - * - * An open source application development framework for PHP 4.3.2 or newer - * - * @package CodeIgniter - * @author ExpressionEngine Dev Team - * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc. - * @license http://codeigniter.com/user_guide/license.html - * @link http://codeigniter.com - * @since Version 1.0 - * @filesource - */ - -// ------------------------------------------------------------------------ - -/** - * Validation Class - * - * @package CodeIgniter - * @subpackage Libraries - * @category Validation - * @author ExpressionEngine Dev Team - * @link http://codeigniter.com/user_guide/libraries/validation.html - */ -class CI_Validation { - - var $CI; - var $error_string = ''; - var $_error_array = array(); - var $_rules = array(); - var $_fields = array(); - var $_error_messages = array(); - var $_current_field = ''; - var $_safe_form_data = FALSE; - var $_error_prefix = '<p>'; - var $_error_suffix = '</p>'; - - - - /** - * Constructor - * - */ - function CI_Validation() - { - $this->CI =& get_instance(); - - if (function_exists('mb_internal_encoding')) - { - mb_internal_encoding($this->CI->config->item('charset')); - } - - log_message('debug', "Validation Class Initialized"); - } - - // -------------------------------------------------------------------- - - /** - * Set Fields - * - * This function takes an array of field names as input - * and generates class variables with the same name, which will - * either be blank or contain the $_POST value corresponding to it - * - * @access public - * @param string - * @param string - * @return void - */ - function set_fields($data = '', $field = '') - { - if ($data == '') - { - if (count($this->_fields) == 0) - { - return FALSE; - } - } - else - { - if ( ! is_array($data)) - { - $data = array($data => $field); - } - - if (count($data) > 0) - { - $this->_fields = $data; - } - } - - foreach($this->_fields as $key => $val) - { - $this->$key = ( ! isset($_POST[$key])) ? '' : $this->prep_for_form($_POST[$key]); - - $error = $key.'_error'; - if ( ! isset($this->$error)) - { - $this->$error = ''; - } - } - } - - // -------------------------------------------------------------------- - - /** - * Set Rules - * - * This function takes an array of field names and validation - * rules as input ad simply stores is for use later. - * - * @access public - * @param mixed - * @param string - * @return void - */ - function set_rules($data, $rules = '') - { - if ( ! is_array($data)) - { - if ($rules == '') - return; - - $data = array($data => $rules); - } - - foreach ($data as $key => $val) - { - $this->_rules[$key] = $val; - } - } - - // -------------------------------------------------------------------- - - /** - * Set Error Message - * - * Lets users set their own error messages on the fly. Note: The key - * name has to match the function name that it corresponds to. - * - * @access public - * @param string - * @param string - * @return string - */ - function set_message($lang, $val = '') - { - if ( ! is_array($lang)) - { - $lang = array($lang => $val); - } - - $this->_error_messages = array_merge($this->_error_messages, $lang); - } - - // -------------------------------------------------------------------- - - /** - * Set The Error Delimiter - * - * Permits a prefix/suffix to be added to each error message - * - * @access public - * @param string - * @param string - * @return void - */ - function set_error_delimiters($prefix = '<p>', $suffix = '</p>') - { - $this->_error_prefix = $prefix; - $this->_error_suffix = $suffix; - } - - // -------------------------------------------------------------------- - - /** - * Run the Validator - * - * This function does all the work. - * - * @access public - * @return bool - */ - function run() - { - // Do we even have any data to process? Mm? - if (count($_POST) == 0 OR count($this->_rules) == 0) - { - return FALSE; - } - - // Load the language file containing error messages - $this->CI->lang->load('validation'); - - // Cycle through the rules and test for errors - foreach ($this->_rules as $field => $rules) - { - //Explode out the rules! - $ex = explode('|', $rules); - - // Is the field required? If not, if the field is blank we'll move on to the next test - if ( ! in_array('required', $ex, TRUE)) - { - if ( ! isset($_POST[$field]) OR $_POST[$field] == '') - { - continue; - } - } - - /* - * Are we dealing with an "isset" rule? - * - * Before going further, we'll see if one of the rules - * is to check whether the item is set (typically this - * applies only to checkboxes). If so, we'll - * test for it here since there's not reason to go - * further - */ - if ( ! isset($_POST[$field])) - { - if (in_array('isset', $ex, TRUE) OR in_array('required', $ex)) - { - if ( ! isset($this->_error_messages['isset'])) - { - if (FALSE === ($line = $this->CI->lang->line('isset'))) - { - $line = 'The field was not set'; - } - } - else - { - $line = $this->_error_messages['isset']; - } - - // Build the error message - $mfield = ( ! isset($this->_fields[$field])) ? $field : $this->_fields[$field]; - $message = sprintf($line, $mfield); - - // Set the error variable. Example: $this->username_error - $error = $field.'_error'; - $this->$error = $this->_error_prefix.$message.$this->_error_suffix; - $this->_error_array[] = $message; - } - - continue; - } - - /* - * Set the current field - * - * The various prepping functions need to know the - * current field name so they can do this: - * - * $_POST[$this->_current_field] == 'bla bla'; - */ - $this->_current_field = $field; - - // Cycle through the rules! - foreach ($ex As $rule) - { - // Is the rule a callback? - $callback = FALSE; - if (substr($rule, 0, 9) == 'callback_') - { - $rule = substr($rule, 9); - $callback = TRUE; - } - - // Strip the parameter (if exists) from the rule - // Rules can contain a parameter: max_length[5] - $param = FALSE; - if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match)) - { - $rule = $match[1]; - $param = $match[2]; - } - - // Call the function that corresponds to the rule - if ($callback === TRUE) - { - if ( ! method_exists($this->CI, $rule)) - { - continue; - } - - $result = $this->CI->$rule($_POST[$field], $param); - - // If the field isn't required and we just processed a callback we'll move on... - if ( ! in_array('required', $ex, TRUE) AND $result !== FALSE) - { - continue 2; - } - - } - else - { - if ( ! method_exists($this, $rule)) - { - /* - * Run the native PHP function if called for - * - * If our own wrapper function doesn't exist we see - * if a native PHP function does. Users can use - * any native PHP function call that has one param. - */ - if (function_exists($rule)) - { - $_POST[$field] = $rule($_POST[$field]); - $this->$field = $_POST[$field]; - } - - continue; - } - - $result = $this->$rule($_POST[$field], $param); - } - - // Did the rule test negatively? If so, grab the error. - if ($result === FALSE) - { - if ( ! isset($this->_error_messages[$rule])) - { - if (FALSE === ($line = $this->CI->lang->line($rule))) - { - $line = 'Unable to access an error message corresponding to your field name.'; - } - } - else - { - $line = $this->_error_messages[$rule]; - } - - // Build the error message - $mfield = ( ! isset($this->_fields[$field])) ? $field : $this->_fields[$field]; - $mparam = ( ! isset($this->_fields[$param])) ? $param : $this->_fields[$param]; - $message = sprintf($line, $mfield, $mparam); - - // Set the error variable. Example: $this->username_error - $error = $field.'_error'; - $this->$error = $this->_error_prefix.$message.$this->_error_suffix; - - // Add the error to the error array - $this->_error_array[] = $message; - continue 2; - } - } - - } - - $total_errors = count($this->_error_array); - - /* - * Recompile the class variables - * - * If any prepping functions were called the $_POST data - * might now be different then the corresponding class - * variables so we'll set them anew. - */ - if ($total_errors > 0) - { - $this->_safe_form_data = TRUE; - } - - $this->set_fields(); - - // Did we end up with any errors? - if ($total_errors == 0) - { - return TRUE; - } - - // Generate the error string - foreach ($this->_error_array as $val) - { - $this->error_string .= $this->_error_prefix.$val.$this->_error_suffix."\n"; - } - - return FALSE; - } - - // -------------------------------------------------------------------- - - /** - * Required - * - * @access public - * @param string - * @return bool - */ - function required($str) - { - if ( ! is_array($str)) - { - return (trim($str) == '') ? FALSE : TRUE; - } - else - { - return ( ! empty($str)); - } - } - - // -------------------------------------------------------------------- - - /** - * Match one field to another - * - * @access public - * @param string - * @param field - * @return bool - */ - function matches($str, $field) - { - if ( ! isset($_POST[$field])) - { - return FALSE; - } - - return ($str !== $_POST[$field]) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Minimum Length - * - * @access public - * @param string - * @param value - * @return bool - */ - function min_length($str, $val) - { - if (preg_match("/[^0-9]/", $val)) - { - return FALSE; - } - - if (function_exists('mb_strlen')) - { - return (mb_strlen($str) < $val) ? FALSE : TRUE; - } - - return (strlen($str) < $val) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Max Length - * - * @access public - * @param string - * @param value - * @return bool - */ - function max_length($str, $val) - { - if (preg_match("/[^0-9]/", $val)) - { - return FALSE; - } - - if (function_exists('mb_strlen')) - { - return (mb_strlen($str) > $val) ? FALSE : TRUE; - } - - return (strlen($str) > $val) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Exact Length - * - * @access public - * @param string - * @param value - * @return bool - */ - function exact_length($str, $val) - { - if (preg_match("/[^0-9]/", $val)) - { - return FALSE; - } - - if (function_exists('mb_strlen')) - { - return (mb_strlen($str) != $val) ? FALSE : TRUE; - } - - return (strlen($str) != $val) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Valid Email - * - * @access public - * @param string - * @return bool - */ - function valid_email($str) - { - return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Valid Emails - * - * @access public - * @param string - * @return bool - */ - function valid_emails($str) - { - if (strpos($str, ',') === FALSE) - { - return $this->valid_email(trim($str)); - } - - foreach(explode(',', $str) as $email) - { - if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE) - { - return FALSE; - } - } - - return TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Validate IP Address - * - * @access public - * @param string - * @return string - */ - function valid_ip($ip) - { - return $this->CI->input->valid_ip($ip); - } - - // -------------------------------------------------------------------- - - /** - * Alpha - * - * @access public - * @param string - * @return bool - */ - function alpha($str) - { - return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Alpha-numeric - * - * @access public - * @param string - * @return bool - */ - function alpha_numeric($str) - { - return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Alpha-numeric with underscores and dashes - * - * @access public - * @param string - * @return bool - */ - function alpha_dash($str) - { - return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Numeric - * - * @access public - * @param string - * @return bool - */ - function numeric($str) - { - return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str); - - } - - // -------------------------------------------------------------------- - - /** - * Is Numeric - * - * @access public - * @param string - * @return bool - */ - function is_numeric($str) - { - return ( ! is_numeric($str)) ? FALSE : TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Integer - * - * @access public - * @param string - * @return bool - */ - function integer($str) - { - return (bool)preg_match( '/^[\-+]?[0-9]+$/', $str); - } - - // -------------------------------------------------------------------- - - /** - * Is a Natural number (0,1,2,3, etc.) - * - * @access public - * @param string - * @return bool - */ - function is_natural($str) - { - return (bool)preg_match( '/^[0-9]+$/', $str); - } - - // -------------------------------------------------------------------- - - /** - * Is a Natural number, but not a zero (1,2,3, etc.) - * - * @access public - * @param string - * @return bool - */ - function is_natural_no_zero($str) - { - if ( ! preg_match( '/^[0-9]+$/', $str)) - { - return FALSE; - } - - if ($str == 0) - { - return FALSE; - } - - return TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Valid Base64 - * - * Tests a string for characters outside of the Base64 alphabet - * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045 - * - * @access public - * @param string - * @return bool - */ - function valid_base64($str) - { - return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str); - } - - // -------------------------------------------------------------------- - - /** - * Set Select - * - * Enables pull-down lists to be set to the value the user - * selected in the event of an error - * - * @access public - * @param string - * @param string - * @return string - */ - function set_select($field = '', $value = '') - { - if ($field == '' OR $value == '' OR ! isset($_POST[$field])) - { - return ''; - } - - if ($_POST[$field] == $value) - { - return ' selected="selected"'; - } - } - - // -------------------------------------------------------------------- - - /** - * Set Radio - * - * Enables radio buttons to be set to the value the user - * selected in the event of an error - * - * @access public - * @param string - * @param string - * @return string - */ - function set_radio($field = '', $value = '') - { - if ($field == '' OR $value == '' OR ! isset($_POST[$field])) - { - return ''; - } - - if ($_POST[$field] == $value) - { - return ' checked="checked"'; - } - } - - // -------------------------------------------------------------------- - - /** - * Set Checkbox - * - * Enables checkboxes to be set to the value the user - * selected in the event of an error - * - * @access public - * @param string - * @param string - * @return string - */ - function set_checkbox($field = '', $value = '') - { - if ($field == '' OR $value == '' OR ! isset($_POST[$field])) - { - return ''; - } - - if ($_POST[$field] == $value) - { - return ' checked="checked"'; - } - } - - // -------------------------------------------------------------------- - - /** - * Prep data for form - * - * This function allows HTML to be safely shown in a form. - * Special characters are converted. - * - * @access public - * @param string - * @return string - */ - function prep_for_form($data = '') - { - if (is_array($data)) - { - foreach ($data as $key => $val) - { - $data[$key] = $this->prep_for_form($val); - } - - return $data; - } - - if ($this->_safe_form_data == FALSE OR $data == '') - { - return $data; - } - - return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data)); - } - - // -------------------------------------------------------------------- - - /** - * Prep URL - * - * @access public - * @param string - * @return string - */ - function prep_url($str = '') - { - if ($str == 'http://' OR $str == '') - { - $_POST[$this->_current_field] = ''; - return; - } - - if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://') - { - $str = 'http://'.$str; - } - - $_POST[$this->_current_field] = $str; - } - - // -------------------------------------------------------------------- - - /** - * Strip Image Tags - * - * @access public - * @param string - * @return string - */ - function strip_image_tags($str) - { - $_POST[$this->_current_field] = $this->CI->input->strip_image_tags($str); - } - - // -------------------------------------------------------------------- - - /** - * XSS Clean - * - * @access public - * @param string - * @return string - */ - function xss_clean($str) - { - $_POST[$this->_current_field] = $this->CI->input->xss_clean($str); - } - - // -------------------------------------------------------------------- - - /** - * Convert PHP tags to entities - * - * @access public - * @param string - * @return string - */ - function encode_php_tags($str) - { - $_POST[$this->_current_field] = str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str); - } - -} -// END Validation Class - -/* End of file Validation.php */ -/* Location: ./system/libraries/Validation.php */
\ No newline at end of file diff --git a/user_guide/changelog.html b/user_guide/changelog.html index 14d173ab8..02cf6d06f 100644 --- a/user_guide/changelog.html +++ b/user_guide/changelog.html @@ -74,6 +74,7 @@ Hg Tag: </p> <li>Added <kbd>$config['directory_trigger']</kbd> to the config file so that a controller sub-directory can be specified when running _GET strings instead of URI segments.</li> <li>Added ability to set "Package" paths - specific paths where the Loader and Config classes should try to look first for a requested file. This allows distribution of sub-applications with their own libraries, models, config files, etc. in a single "package" directory. See the <a href="libraries/loader.html">Loader class</a> documentation for more details.</li> <li>In-development code is now hosted at <a href="http://bitbucket.org/ellislab/codeigniter/">BitBucket</a>.</li> + <li>Removed the deprecated Validation Class.</li> </ul> <li>Libraries <ul> @@ -496,7 +497,7 @@ Hg Tag: 1.6.2</p> <li>The MySQLi forge class is now in sync with MySQL forge. </li> <li>Added the ability to set CRLF settings via config in the <a href="libraries/email.html">Email</a> class.</li> <li><a href="libraries/unit_testing.html">Unit Testing</a> results are now colour coded, and a change was made to the default template of results.</li> - <li>Added a valid_emails rule to the <a href="libraries/validation.html">Validation</a> class.</li> + <li>Added a valid_emails rule to the Validation class.</li> <li>The <a href="libraries/zip.html">Zip class</a> now exits within <kbd>download()</kbd>.</li> <li>The <a href="libraries/zip.html">Zip class</a> has undergone a substantial re-write for speed and clarity (thanks stanleyxu for the hard work and code contribution in bug report #3425!)</li> </ul> @@ -682,8 +683,8 @@ Hg Tag: 1.6.1</p> <li>Removed 'last_visit' from the Session class.</li> <li>Added a language entry for valid_ip validation error.</li> <li>Modified prep_for_form() in the Validation class to accept arrays, adding support for POST array validation (via callbacks only)</li> - <li>Added an "integer" rule into the <a href="./libraries/validation.html">Validation</a> library.</li> - <li>Added valid_base64() to the <a href="./libraries/validation.html">Validation</a> library.</li> + <li>Added an "integer" rule into the Validation library.</li> + <li>Added valid_base64() to the Validation library.</li> <li>Documented clear() in the <a href="../libraries/image_lib.html">Image Processing</a> library.</li> <li>Changed the behaviour of custom callbacks so that they no longer trigger the "required" rule. </li> <li>Modified Upload class $_FILES error messages to be more precise.</li> @@ -769,8 +770,8 @@ Hg Tag: 1.6.1</p> <li>Fixed a bug in database driver where num_rows property wasn't getting updated.</li> <li>Fixed a bug in the <a href="./libraries/file_uploading.html">upload library</a> when allowed_files wasn't defined.</li> <li>Fixed a bug in <kbd>word_wrap()</kbd> of the Text Helper that incorrectly referenced an object. </li> - <li>Fixed a bug in <a href="./libraries/validation.html">Validation</a> where <kbd>valid_ip()</kbd> wasn't called properly.</li> - <li>Fixed a bug in <a href="./libraries/validation.html">Validation</a> where individual error messages for checkboxes wasn't supported.</li> + <li>Fixed a bug in Validation where <kbd>valid_ip()</kbd> wasn't called properly.</li> + <li>Fixed a bug in Validation where individual error messages for checkboxes wasn't supported.</li> <li>Fixed a bug in captcha calling an invalid PHP function.</li> <li>Fixed a bug in the cookie helper "set_cookie" function. It was not honoring the config settings.</li> <li>Fixed a bug that was making validation callbacks required even when not set as such.</li> diff --git a/user_guide/libraries/validation.html b/user_guide/libraries/validation.html deleted file mode 100644 index d62ca01be..000000000 --- a/user_guide/libraries/validation.html +++ /dev/null @@ -1,740 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> -<head> - -<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -<title>Form Validation : CodeIgniter User Guide</title> - -<style type='text/css' media='all'>@import url('../userguide.css');</style> -<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> - -<script type="text/javascript" src="../nav/nav.js"></script> -<script type="text/javascript" src="../nav/prototype.lite.js"></script> -<script type="text/javascript" src="../nav/moo.fx.js"></script> -<script type="text/javascript" src="../nav/user_guide_menu.js"></script> - -<meta http-equiv='expires' content='-1' /> -<meta http-equiv= 'pragma' content='no-cache' /> -<meta name='robots' content='all' /> -<meta name='author' content='ExpressionEngine Dev Team' /> -<meta name='description' content='CodeIgniter User Guide' /> -</head> -<body> - -<!-- START NAVIGATION --> -<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> -<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> -<div id="masthead"> -<table cellpadding="0" cellspacing="0" border="0" style="width:100%"> -<tr> -<td><h1>CodeIgniter User Guide Version 2.0.0</h1></td> -<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> -</tr> -</table> -</div> -<!-- END NAVIGATION --> - - -<!-- START BREADCRUMB --> -<table cellpadding="0" cellspacing="0" border="0" style="width:100%"> -<tr> -<td id="breadcrumb"> -<a href="http://codeigniter.com/">CodeIgniter Home</a> › -<a href="../index.html">User Guide Home</a> › -Form Validation -</td> -<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" /> <input type="submit" class="submit" name="sa" value="Go" /></form></td> -</tr> -</table> -<!-- END BREADCRUMB --> - -<br clear="all" /> - - -<!-- START CONTENT --> -<div id="content"> - -<p class="important"> - This library has been deprecated. Use of the form_validation library is encouraged. -</p> - -<h1>Form Validation</h1> - -<p>Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:</p> - -<ol> -<li>A form is displayed.</li> -<li>You fill it in and submit it.</li> -<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> -<li>This process continues until you have submitted a valid form.</li> -</ol> - -<p>On the receiving end, the script must:</p> - -<ol> -<li>Check for required data.</li> -<li>Verify that the data is of the correct type, and meets the correct criteria. (For example, if a username is submitted -it must be validated to contain only permitted characters. It must be of a minimum length, -and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.)</li> -<li>Sanitize the data for security.</li> -<li>Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)</li> -<li>Prep the data for insertion in the database.</li> -</ol> - - -<p>Although there is nothing complex about the above process, it usually requires a significant -amount of code, and to display error messages, various control structures are usually placed within the form HTML. -Form validation, while simple to create, is generally very messy and tedious to implement.</p> - -<dfn>CodeIgniter provides a comprehensive validation framework that truly minimizes the amount of code you'll write. -It also removes all control structures from your form HTML, permitting it to be clean and free of code.</dfn> - -<h2>Overview</h2> - -<p>In order to implement CodeIgniter's form validation you'll need three things:</p> - -<ol> -<li>A <a href="../general/views.html">View</a> file containing the form.</li> -<li>A View file containing a "success" message to be displayed upon successful submission.</li> -<li>A <a href="../general/controllers.html">controller</a> function to receive and process the submitted data.</li> -</ol> - -<p>Let's create those three things, using a member sign-up form as the example.</p> - -<h2>The Form</h2> - -<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> -folder:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="30"><html> -<head> -<title>My Form</title> -</head> -<body> - -<?php echo $this->validation->error_string; ?> - -<?php echo form_open('form'); ?> - -<h5>Username</h5> -<input type="text" name="username" value="" size="50" /> - -<h5>Password</h5> -<input type="text" name="password" value="" size="50" /> - -<h5>Password Confirm</h5> -<input type="text" name="passconf" value="" size="50" /> - -<h5>Email Address</h5> -<input type="text" name="email" value="" size="50" /> - -<div><input type="submit" value="Submit" /></div> - -</form> - -</body> -</html> -</textarea> - - -<h2>The Success Page</h2> - - -<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> -folder:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="14"> -<html> -<head> -<title>My Form</title> -</head> -<body> - -<h3>Your form was successfully submitted!</h3> - -<p><?php echo anchor('form', 'Try it again!'); ?></p> - -</body> -</html> -</textarea> - - -<h2>The Controller</h2> - -<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> -folder:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="21"><?php - -class Form extends Controller { - - function index() - { - $this->load->helper(array('form', 'url')); - - $this->load->library('validation'); - - if ($this->validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } -} -?></textarea> - - -<h2>Try it!</h2> - -<p>To try your form, visit your site using a URL similar to this one:</p> - -<code>example.com/index.php/<var>form</var>/</code> - -<p><strong>If you submit the form you should simply see the form reload. That's because you haven't set up any validation -rules yet, which we'll get to in a moment.</strong></p> - - -<h2>Explanation</h2> - -<p>You'll notice several things about the above pages:</p> - -<p>The <dfn>form</dfn> (myform.php) is a standard web form with a couple exceptions:</p> - -<ol> -<li>It uses a <dfn>form helper</dfn> to create the form opening. -Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper -is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable -and flexible in the event your URLs change.</li> - -<li>At the top of the form you'll notice the following variable: -<code><?php echo $this->validation->error_string; ?></code> - -<p>This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.</p> -</li> -</ol> - -<p>The <dfn>controller</dfn> (form.php) has one function: <dfn>index()</dfn>. This function initializes the validation class and -loads the <var>form helper</var> and <var>URL helper</var> used by your view files. It also <samp>runs</samp> -the validation routine. Based on -whether the validation was successful it either presents the form or the success page.</p> - -<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> -function only returns "true" if it has successfully applied your rules without any of them failing.</strong></p> - - -<h2>Setting Validation Rules</h2> - -<p>CodeIgniter 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 -at the same time. Let's see it in action, we'll explain it afterwards.</p> - -<p>In your <dfn>controller</dfn> (form.php), add this code just below the validation initialization function:</p> - -<code>$rules['username'] = "required";<br /> -$rules['password'] = "required";<br /> -$rules['passconf'] = "required";<br /> -$rules['email'] = "required";<br /> -<br /> -$this->validation->set_rules($rules);</code> - -<p>Your controller should now look like this:</p> - -<textarea class="textarea" style="width:100%" cols="50" rows="28"><?php - -class Form extends Controller { - - function index() - { - $this->load->helper(array('form', 'url')); - - $this->load->library('validation'); - - $rules['username'] = "required"; - $rules['password'] = "required"; - $rules['passconf'] = "required"; - $rules['email'] = "required"; - - $this->validation->set_rules($rules); - - if ($this->validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } -} -?></textarea> - -<p><dfn>Now submit the form with the fields blank and you should see the error message. -If you submit the form with all the fields populated you'll see your success page.</dfn></p> - -<p class="important"><strong>Note:</strong> The form fields are not yet being re-populated with the data when -there is an error. We'll get to that shortly, once we're through explaining the validation rules.</p> - - -<h2>Changing the Error Delimiters</h2> - -<p>By default, the system adds a paragraph tag (<p>) around each error message shown. You can easily change these delimiters with -this code, placed in your controller:</p> - -<code>$this->validation->set_error_delimiters('<kbd><div class="error"></kbd>', '<kbd></div></kbd>');</code> - -<p>In this example, we've switched to using div tags.</p> - -<h2>Cascading Rules</h2> - -<p>CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules array like this:</p> - - -<code>$rules['username'] = "required|min_length[5]|max_length[12]";<br /> -$rules['password'] = "required|matches[passconf]";<br /> -$rules['passconf'] = "required";<br /> -$rules['email'] = "required|valid_email";</code> - -<p>The above code requires that:</p> - -<ol> -<li>The username field be no shorter than 5 characters and no longer than 12.</li> -<li>The password field must match the password confirmation field.</li> -<li>The email field must contain a valid email address.</li> -</ol> - -<p>Give it a try!</p> - -<p class="important"><strong>Note:</strong> There are numerous rules available which you can read about in the validation reference.</p> - - -<h2>Prepping Data</h2> - -<p>In addition to the validation functions like the ones we used above, you can also prep your data in various ways. -For example, you can set up rules like this:</p> - -<code>$rules['username'] = "<kbd>trim</kbd>|required|min_length[5]|max_length[12]|<kbd>xss_clean</kbd>";<br /> -$rules['password'] = "<kbd>trim</kbd>|required|matches[passconf]|<kbd>md5</kbd>";<br /> -$rules['passconf'] = "<kbd>trim</kbd>|required";<br /> -$rules['email'] = "<kbd>trim</kbd>|required|valid_email";</code> - -<p>In the above example, we are "trimming" the fields, converting the password to MD5, and running the username through -the "xss_clean" function, which removes malicious data.</p> - -<p class="important"><strong>Any native PHP function that accepts one parameter can be used as a rule, like <dfn>htmlspecialchars</dfn>, -<dfn>trim</dfn>, <dfn>MD5</dfn>, etc.</strong></p> - -<p><strong>Note:</strong> You will generally want to use the prepping functions <strong>after</strong> -the validation rules so if there is an error, the original data will be shown in the form.</p> - -<h2>Callbacks: Your own Validation Functions</h2> - -<p>The validation system supports callbacks to your own validation functions. This permits you to extend the validation class -to 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 -create a callback function that does that. Let's create a simple example.</p> - -<p>In your controller, change the "username" rule to this:</p> - -<code>$rules['username'] = "callback_username_check"; </code> - -<p>Then add a new function called <dfn>username_check</dfn> to your controller. Here's how your controller should look:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="44"><?php - -class Form extends Controller { - - function index() - { - $this->load->helper(array('form', 'url')); - - $this->load->library('validation'); - - $rules['username'] = "callback_username_check"; - $rules['password'] = "required"; - $rules['passconf'] = "required"; - $rules['email'] = "required"; - - $this->validation->set_rules($rules); - - if ($this->validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } - - function username_check($str) - { - if ($str == 'test') - { - $this->validation->set_message('username_check', 'The %s field can not be the word "test"'); - return FALSE; - } - else - { - return TRUE; - } - } - -} -?></textarea> - -<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 -callback function for you to process.</p> - -<p><strong>To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix.</strong></p> - -<p>The error message was set using the <dfn>$this->validation->set_message</dfn> function. -Just remember that the message key (the first parameter) must match your function name.</p> - -<p class="important"><strong>Note:</strong> You can apply your own custom error messages to any rule, just by setting the -message similarly. For example, to change the message for the "required" rule you will do this:</p> - -<code>$this->validation->set_message('required', 'Your custom message here');</code> - -<h2>Re-populating the form</h2> - -<p>Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. -This is done similarly to your rules. Add the following code to your controller, just below your rules:</p> - -<code>$fields['username'] = 'Username';<br /> -$fields['password'] = 'Password';<br /> -$fields['passconf'] = 'Password Confirmation';<br /> -$fields['email'] = 'Email Address';<br /> -<br /> -$this->validation->set_fields($fields);</code> - -<p>The array keys are the actual names of the form fields, the value represents the full name that you want shown in the -error message.</p> - -<p>The index function of your controller should now look like this:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="30">function index() -{ - $this->load->helper(array('form', 'url')); - - $this->load->library('validation'); - - $rules['username'] = "required"; - $rules['password'] = "required"; - $rules['passconf'] = "required"; - $rules['email'] = "required"; - - $this->validation->set_rules($rules); - - $fields['username'] = 'Username'; - $fields['password'] = 'Password'; - $fields['passconf'] = 'Password Confirmation'; - $fields['email'] = 'Email Address'; - - $this->validation->set_fields($fields); - - if ($this->validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } -}</textarea> - - -<p>Now open your <dfn>myform.php</dfn> view file and update the value in each field so that it has an attribute corresponding to its name:</p> - - -<textarea class="textarea" style="width:100%" cols="50" rows="30"> -<html> -<head> -<title>My Form</title> -</head> -<body> - -<?php echo $this->validation->error_string; ?> - -<?php echo form_open('form'); ?> - -<h5>Username</h5> -<input type="text" name="username" value="<?php echo $this->validation->username;?>" size="50" /> - -<h5>Password</h5> -<input type="text" name="password" value="<?php echo $this->validation->password;?>" size="50" /> - -<h5>Password Confirm</h5> -<input type="text" name="passconf" value="<?php echo $this->validation->passconf;?>" size="50" /> - -<h5>Email Address</h5> -<input type="text" name="email" value="<?php echo $this->validation->email;?>" size="50" /> - -<div><input type="submit" value="Submit" /></div> - -</form> - -</body> -</html> -</textarea> - - -<p>Now reload your page and submit the form so that it triggers an error. Your form fields should be populated -and the error messages will contain a more relevant field name.</p> - - - -<h2>Showing Errors Individually</h2> - -<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> - - -<textarea class="textarea" style="width:100%" cols="50" rows="20"> -<h5>Username</h5> -<?php echo $this->validation->username_error; ?> -<input type="text" name="username" value="<?php echo $this->validation->username;?>" size="50" /> - -<h5>Password</h5> -<?php echo $this->validation->password_error; ?> -<input type="text" name="password" value="<?php echo $this->validation->password;?>" size="50" /> - -<h5>Password Confirm</h5> -<?php echo $this->validation->passconf_error; ?> -<input type="text" name="passconf" value="<?php echo $this->validation->passconf;?>" size="50" /> - -<h5>Email Address</h5> -<?php echo $this->validation->email_error; ?> -<input type="text" name="email" value="<?php echo $this->validation->email;?>" size="50" /></textarea> - -<p>If there are no errors, nothing will be shown. If there is an error, the message will appear, wrapped in the delimiters you -have set (<p> tags by default).</p> - -<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> -function described earlier. The errors will be turned into variables that have "_error" after your field name. -For example, your "username" error will be available at:<br /><dfn>$this->validation->username_error</dfn>.</p> - - -<h2>Rule Reference</h2> - -<p>The following is a list of all the native rules that are available to use:</p> - - - -<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> -<tr> -<th>Rule</th> -<th>Parameter</th> -<th>Description</th> -<th>Example</th> -</tr><tr> - -<td class="td"><strong>required</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element is empty.</td> -<td class="td"> </td> -</tr><tr> - -<td class="td"><strong>matches</strong></td> -<td class="td">Yes</td> -<td class="td">Returns FALSE if the form element does not match the one in the parameter.</td> -<td class="td">matches[form_item]</td> -</tr><tr> - -<td class="td"><strong>min_length</strong></td> -<td class="td">Yes</td> -<td class="td">Returns FALSE if the form element is shorter then the parameter value.</td> -<td class="td">min_length[6]</td> -</tr><tr> - -<td class="td"><strong>max_length</strong></td> -<td class="td">Yes</td> -<td class="td">Returns FALSE if the form element is longer then the parameter value.</td> -<td class="td">max_length[12]</td> -</tr><tr> - -<td class="td"><strong>exact_length</strong></td> -<td class="td">Yes</td> -<td class="td">Returns FALSE if the form element is not exactly the parameter value.</td> -<td class="td">exact_length[8]</td> -</tr><tr> - -<td class="td"><strong>alpha</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element contains anything other than alphabetical characters.</td> -<td class="td"> </td> -</tr><tr> - -<td class="td"><strong>alpha_numeric</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters.</td> -<td class="td"> </td> -</tr><tr> - -<td class="td"><strong>alpha_dash</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.</td> -<td class="td"> </td> -</tr> -<tr> - <td class="td"><strong>numeric</strong></td> - <td class="td">No</td> - <td class="td">Returns FALSE if the form element contains anything other than numeric characters.</td> - <td class="td"> </td> -</tr> -<tr> - -<td class="td"><strong>integer</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element contains anything other than an integer.</td> -<td class="td"> </td> -</tr><tr> - -<td class="td"><strong>valid_email</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the form element does not contain a valid email address.</td> -<td class="td"> </td> -</tr> -<tr> - <td class="td"><strong>valid_emails</strong></td> - <td class="td">No</td> - <td class="td">Returns FALSE if any value provided in a comma separated list is not a valid email.</td> - <td class="td"> </td> -</tr> -<tr> -<td class="td"><strong>valid_ip</strong></td> -<td class="td">No</td> -<td class="td">Returns FALSE if the supplied IP is not valid.</td> -<td class="td"> </td> -</tr> -<tr> - <td class="td"><strong>valid_base64</strong></td> - <td class="td">No</td> - <td class="td">Returns FALSE if the supplied string contains anything other than valid Base64 characters.</td> - <td class="td"> </td> -</tr> -</table> - -<p><strong>Note:</strong> These rules can also be called as discrete functions. For example:</p> - -<code>$this->validation->required($string);</code> - -<p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter.</p> - - - -<h2>Prepping Reference</h2> - -<p>The following is a list of all the prepping functions that are available to use:</p> - - - -<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> -<tr> -<th>Name</th> -<th>Parameter</th> -<th>Description</th> -</tr><tr> - -<td class="td"><strong>xss_clean</strong></td> -<td class="td">No</td> -<td class="td">Runs the data through the XSS filtering function, described in the <a href="input.html">Input Class</a> page.</td> -</tr><tr> - -<td class="td"><strong>prep_for_form</strong></td> -<td class="td">No</td> -<td class="td">Converts special characters so that HTML data can be shown in a form field without breaking it.</td> -</tr><tr> - -<td class="td"><strong>prep_url</strong></td> -<td class="td">No</td> -<td class="td">Adds "http://" to URLs if missing.</td> -</tr><tr> - -<td class="td"><strong>strip_image_tags</strong></td> -<td class="td">No</td> -<td class="td">Strips the HTML from image tags leaving the raw URL.</td> -</tr><tr> - -<td class="td"><strong>encode_php_tags</strong></td> -<td class="td">No</td> -<td class="td">Converts PHP tags to entities.</td> -</tr> - -</table> - -<p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter, -like <kbd>trim</kbd>, <kbd>htmlspecialchars</kbd>, <kbd>urldecode</kbd>, etc.</p> - - -<h2>Setting Custom Error Messages</h2> - -<p>All of the native error messages are located in the following language file: <dfn>language/english/validation_lang.php</dfn></p> - -<p>To set your own custom message you can either edit that file, or use the following function:</p> - -<code>$this->validation->set_message('<var>rule</var>', '<var>Error Message</var>');</code> - -<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> - - -<h2>Dealing with Select Menus, Radio Buttons, and Checkboxes</h2> - -<p>If you use select menus, radio buttons or checkboxes, you will want the state of -these items to be retained in the event of an error. The Validation class has three functions that help you do this:</p> - -<h2>set_select()</h2> - -<p>Permits you to display the menu item that was selected. The first parameter -must contain the name of the select menu, the second parameter must contain the value of -each item. Example:</p> - -<code> -<select name="myselect"><br /> -<option value="one" <dfn><?php echo $this->validation->set_select('myselect', 'one'); ?></dfn> >One</option><br /> -<option value="two" <dfn><?php echo $this->validation->set_select('myselect', 'two'); ?></dfn> >Two</option><br /> -<option value="three" <dfn><?php echo $this->validation->set_select('myselect', 'three'); ?></dfn> >Three</option><br /> -</select> -</code> - - -<h2>set_checkbox()</h2> - -<p>Permits you to display a checkbox in the state it was submitted. The first parameter -must contain the name of the checkbox, the second parameter must contain its value. Example:</p> - -<code><input type="checkbox" name="mycheck" value="1" <dfn><?php echo $this->validation->set_checkbox('mycheck', '1'); ?></dfn> /></code> - - -<h2>set_radio()</h2> - -<p>Permits you to display radio buttons in the state they were submitted. The first parameter -must contain the name of the radio button, the second parameter must contain its value. Example:</p> - -<code><input type="radio" name="myradio" value="1" <dfn><?php echo $this->validation->set_radio('myradio', '1'); ?></dfn> /></code> - - - - - -</div> -<!-- END CONTENT --> - - -<div id="footer"> -<p> -Previous Topic: <a href="user_agent.html">User Agent Class</a> - · -<a href="#top">Top of Page</a> · -<a href="../index.html">User Guide Home</a> · -Next Topic: <a href="xmlrpc.html">XML-RPC Class</a> -</p> -<p><a href="http://codeigniter.com">CodeIgniter</a> · Copyright © 2006-2010 · <a href="http://ellislab.com/">EllisLab, Inc.</a></p> -</div> - -</body> -</html>
\ No newline at end of file |