From ef88a906ed8b2050f4c6e6d8fbd73cc5b6adc7a3 Mon Sep 17 00:00:00 2001 From: Greg Aker Date: Wed, 14 Apr 2010 18:22:23 -0500 Subject: Removing deprecated Validation class. Form_validation going forward! Removed references to the validation classes documentation page in the changelog as well. --- system/libraries/Validation.php | 875 ----------------------------------- user_guide/changelog.html | 11 +- user_guide/libraries/validation.html | 740 ----------------------------- 3 files changed, 6 insertions(+), 1620 deletions(-) delete mode 100644 system/libraries/Validation.php delete mode 100644 user_guide/libraries/validation.html 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 @@ -'; - var $_error_suffix = '

'; - - - - /** - * 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 = '

', $suffix = '

') - { - $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(''), 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 12a4dc92f..cfb7396c6 100644 --- a/user_guide/changelog.html +++ b/user_guide/changelog.html @@ -74,6 +74,7 @@ Hg Tag:

  • Added $config['directory_trigger'] to the config file so that a controller sub-directory can be specified when running _GET strings instead of URI segments.
  • 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 Loader class documentation for more details.
  • In-development code is now hosted at BitBucket.
  • +
  • Removed the deprecated Validation Class.
  • Libraries @@ -680,8 +681,8 @@ Hg Tag: 1.6.1

  • Removed 'last_visit' from the Session class.
  • Added a language entry for valid_ip validation error.
  • Modified prep_for_form() in the Validation class to accept arrays, adding support for POST array validation (via callbacks only)
  • -
  • Added an "integer" rule into the Validation library.
  • -
  • Added valid_base64() to the Validation library.
  • +
  • Added an "integer" rule into the Validation library.
  • +
  • Added valid_base64() to the Validation library.
  • Documented clear() in the Image Processing library.
  • Changed the behaviour of custom callbacks so that they no longer trigger the "required" rule.
  • Modified Upload class $_FILES error messages to be more precise.
  • @@ -767,8 +768,8 @@ Hg Tag: 1.6.1

  • Fixed a bug in database driver where num_rows property wasn't getting updated.
  • Fixed a bug in the upload library when allowed_files wasn't defined.
  • Fixed a bug in word_wrap() of the Text Helper that incorrectly referenced an object.
  • -
  • Fixed a bug in Validation where valid_ip() wasn't called properly.
  • -
  • Fixed a bug in Validation where individual error messages for checkboxes wasn't supported.
  • +
  • Fixed a bug in Validation where valid_ip() wasn't called properly.
  • +
  • Fixed a bug in Validation where individual error messages for checkboxes wasn't supported.
  • Fixed a bug in captcha calling an invalid PHP function.
  • Fixed a bug in the cookie helper "set_cookie" function. It was not honoring the config settings.
  • Fixed a bug that was making validation callbacks required even when not set as such.
  • 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 @@ - - - - - -Form Validation : CodeIgniter User Guide - - - - - - - - - - - - - - - - - - - - -
    - - - - - -

    CodeIgniter User Guide Version 2.0.0

    -
    - - - - - - - - - -
    - - -
    - - - -
    - -

    - This library has been deprecated. Use of the form_validation library is encouraged. -

    - -

    Form Validation

    - -

    Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:

    - -
      -
    1. A form is displayed.
    2. -
    3. You fill it in and submit it.
    4. -
    5. 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.
    6. -
    7. This process continues until you have submitted a valid form.
    8. -
    - -

    On the receiving end, the script must:

    - -
      -
    1. Check for required data.
    2. -
    3. 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.)
    4. -
    5. Sanitize the data for security.
    6. -
    7. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
    8. -
    9. Prep the data for insertion in the database.
    10. -
    - - -

    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.

    - -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. - -

    Overview

    - -

    In order to implement CodeIgniter's form validation you'll need three things:

    - -
      -
    1. A View file containing the form.
    2. -
    3. A View file containing a "success" message to be displayed upon successful submission.
    4. -
    5. A controller function to receive and process the submitted data.
    6. -
    - -

    Let's create those three things, using a member sign-up form as the example.

    - -

    The Form

    - -

    Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ -folder:

    - - - - - -

    The Success Page

    - - -

    Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ -folder:

    - - - - - -

    The Controller

    - -

    Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ -folder:

    - - - - - -

    Try it!

    - -

    To try your form, visit your site using a URL similar to this one:

    - -example.com/index.php/form/ - -

    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.

    - - -

    Explanation

    - -

    You'll notice several things about the above pages:

    - -

    The form (myform.php) is a standard web form with a couple exceptions:

    - -
      -
    1. It uses a form helper 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.
    2. - -
    3. At the top of the form you'll notice the following variable: -<?php echo $this->validation->error_string; ?> - -

      This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.

      -
    4. -
    - -

    The controller (form.php) has one function: index(). This function initializes the validation class and -loads the form helper and URL helper used by your view files. It also runs -the validation routine. Based on -whether the validation was successful it either presents the form or the success page.

    - -

    Since you haven't told the validation class to validate anything yet, it returns "false" (boolean false) by default. The run() -function only returns "true" if it has successfully applied your rules without any of them failing.

    - - -

    Setting Validation Rules

    - -

    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.

    - -

    In your controller (form.php), add this code just below the validation initialization function:

    - -$rules['username'] = "required";
    -$rules['password'] = "required";
    -$rules['passconf'] = "required";
    -$rules['email'] = "required";
    -
    -$this->validation->set_rules($rules);
    - -

    Your controller should now look like this:

    - - - -

    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.

    - -

    Note: 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.

    - - -

    Changing the Error Delimiters

    - -

    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:

    - -$this->validation->set_error_delimiters('<div class="error">', '</div>'); - -

    In this example, we've switched to using div tags.

    - -

    Cascading Rules

    - -

    CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules array like this:

    - - -$rules['username'] = "required|min_length[5]|max_length[12]";
    -$rules['password'] = "required|matches[passconf]";
    -$rules['passconf'] = "required";
    -$rules['email'] = "required|valid_email";
    - -

    The above code requires that:

    - -
      -
    1. The username field be no shorter than 5 characters and no longer than 12.
    2. -
    3. The password field must match the password confirmation field.
    4. -
    5. The email field must contain a valid email address.
    6. -
    - -

    Give it a try!

    - -

    Note: There are numerous rules available which you can read about in the validation reference.

    - - -

    Prepping Data

    - -

    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:

    - -$rules['username'] = "trim|required|min_length[5]|max_length[12]|xss_clean";
    -$rules['password'] = "trim|required|matches[passconf]|md5";
    -$rules['passconf'] = "trim|required";
    -$rules['email'] = "trim|required|valid_email";
    - -

    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.

    - -

    Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, -trim, MD5, etc.

    - -

    Note: You will generally want to use the prepping functions after -the validation rules so if there is an error, the original data will be shown in the form.

    - -

    Callbacks: Your own Validation Functions

    - -

    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.

    - -

    In your controller, change the "username" rule to this:

    - -$rules['username'] = "callback_username_check"; - -

    Then add a new function called username_check to your controller. Here's how your controller should look:

    - - - - -

    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.

    - -

    To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix.

    - -

    The error message was set using the $this->validation->set_message function. -Just remember that the message key (the first parameter) must match your function name.

    - -

    Note: 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:

    - -$this->validation->set_message('required', 'Your custom message here'); - -

    Re-populating the form

    - -

    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:

    - -$fields['username'] = 'Username';
    -$fields['password'] = 'Password';
    -$fields['passconf'] = 'Password Confirmation';
    -$fields['email'] = 'Email Address';
    -
    -$this->validation->set_fields($fields);
    - -

    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.

    - -

    The index function of your controller should now look like this:

    - - - - - -

    Now open your myform.php view file and update the value in each field so that it has an attribute corresponding to its name:

    - - - - - -

    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.

    - - - -

    Showing Errors Individually

    - -

    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:

    - - - - -

    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).

    - -

    Note: To display errors this way you must remember to set your fields using the $this->validation->set_fields -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:
    $this->validation->username_error.

    - - -

    Rule Reference

    - -

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

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    RuleParameterDescriptionExample
    requiredNoReturns FALSE if the form element is empty. 
    matchesYesReturns FALSE if the form element does not match the one in the parameter.matches[form_item]
    min_lengthYesReturns FALSE if the form element is shorter then the parameter value.min_length[6]
    max_lengthYesReturns FALSE if the form element is longer then the parameter value.max_length[12]
    exact_lengthYesReturns FALSE if the form element is not exactly the parameter value.exact_length[8]
    alphaNoReturns FALSE if the form element contains anything other than alphabetical characters. 
    alpha_numericNoReturns FALSE if the form element contains anything other than alpha-numeric characters. 
    alpha_dashNoReturns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes. 
    numericNoReturns FALSE if the form element contains anything other than numeric characters. 
    integerNoReturns FALSE if the form element contains anything other than an integer. 
    valid_emailNoReturns FALSE if the form element does not contain a valid email address. 
    valid_emailsNoReturns FALSE if any value provided in a comma separated list is not a valid email. 
    valid_ipNoReturns FALSE if the supplied IP is not valid. 
    valid_base64NoReturns FALSE if the supplied string contains anything other than valid Base64 characters. 
    - -

    Note: These rules can also be called as discrete functions. For example:

    - -$this->validation->required($string); - -

    Note: You can also use any native PHP functions that permit one parameter.

    - - - -

    Prepping Reference

    - -

    The following is a list of all the prepping functions that are available to use:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameParameterDescription
    xss_cleanNoRuns the data through the XSS filtering function, described in the Input Class page.
    prep_for_formNoConverts special characters so that HTML data can be shown in a form field without breaking it.
    prep_urlNoAdds "http://" to URLs if missing.
    strip_image_tagsNoStrips the HTML from image tags leaving the raw URL.
    encode_php_tagsNoConverts PHP tags to entities.
    - -

    Note: You can also use any native PHP functions that permit one parameter, -like trim, htmlspecialchars, urldecode, etc.

    - - -

    Setting Custom Error Messages

    - -

    All of the native error messages are located in the following language file: language/english/validation_lang.php

    - -

    To set your own custom message you can either edit that file, or use the following function:

    - -$this->validation->set_message('rule', 'Error Message'); - -

    Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.

    - - -

    Dealing with Select Menus, Radio Buttons, and Checkboxes

    - -

    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:

    - -

    set_select()

    - -

    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:

    - - -<select name="myselect">
    -<option value="one" <?php echo $this->validation->set_select('myselect', 'one'); ?> >One</option>
    -<option value="two" <?php echo $this->validation->set_select('myselect', 'two'); ?> >Two</option>
    -<option value="three" <?php echo $this->validation->set_select('myselect', 'three'); ?> >Three</option>
    -</select> -
    - - -

    set_checkbox()

    - -

    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:

    - -<input type="checkbox" name="mycheck" value="1" <?php echo $this->validation->set_checkbox('mycheck', '1'); ?> /> - - -

    set_radio()

    - -

    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:

    - -<input type="radio" name="myradio" value="1" <?php echo $this->validation->set_radio('myradio', '1'); ?> /> - - - - - -
    - - - - - - - \ No newline at end of file -- cgit v1.2.3-24-g4f1b