1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * Form Validation Class
21 * @package CodeIgniter
22 * @subpackage Libraries
23 * @category Validation
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/form_validation.html
27 class CI_Form_validation {
30 var $_field_data = array();
31 var $_config_rules = array();
32 var $_error_array = array();
33 var $_error_messages = array();
34 var $_error_prefix = '<p>';
35 var $_error_suffix = '</p>';
36 var $error_string = '';
37 var $_safe_form_data = FALSE;
44 function CI_Form_validation($rules = array())
46 $this->CI =& get_instance();
48 // Validation rules can be stored in a config file.
49 $this->_config_rules = $rules;
51 // Automatically load the form helper
52 $this->CI->load->helper('form');
54 // Set the character encoding in MB.
55 if (function_exists('mb_internal_encoding'))
57 mb_internal_encoding($this->CI->config->item('charset'));
60 log_message('debug', "Validation Class Initialized");
63 // --------------------------------------------------------------------
68 * This function takes an array of field names and validation
69 * rules as input, validates the info, and stores it
76 function set_rules($field, $label = '', $rules = '')
78 // No reason to set rules if we have no POST data
79 if (count($_POST) == 0)
84 // If an array was passed via the first parameter instead of indidual string
85 // values we cycle through it and recursively call this function.
88 foreach ($field as $row)
90 // Houston, we have a problem...
91 if ( ! isset($row['field']) OR ! isset($row['rules']))
96 // If the field label wasn't passed we use the field name
97 $label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
100 $this->set_rules($row['field'], $label, $row['rules']);
105 // No fields? Nothing to do...
106 if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
111 // If the field label wasn't passed we use the field name
112 $label = ($label == '') ? $field : $label;
114 // Is the field name an array? We test for the existence of a bracket "[" in
115 // the field name to determine this. If it is an array, we break it apart
116 // into its components so that we can fetch the corresponding POST data later
117 if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
119 // Note: Due to a bug in current() that affects some versions
120 // of PHP we can not pass function call directly into it
121 $x = explode('[', $field);
122 $indexes[] = current($x);
124 for ($i = 0; $i < count($matches['0']); $i++)
126 if ($matches['1'][$i] != '')
128 $indexes[] = $matches['1'][$i];
140 // Build our master array
141 $this->_field_data[$field] = array(
145 'is_array' => $is_array,
152 // --------------------------------------------------------------------
157 * Lets users set their own error messages on the fly. Note: The key
158 * name has to match the function name that it corresponds to.
165 function set_message($lang, $val = '')
167 if ( ! is_array($lang))
169 $lang = array($lang => $val);
172 $this->_error_messages = array_merge($this->_error_messages, $lang);
175 // --------------------------------------------------------------------
178 * Set The Error Delimiter
180 * Permits a prefix/suffix to be added to each error message
187 function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
189 $this->_error_prefix = $prefix;
190 $this->_error_suffix = $suffix;
193 // --------------------------------------------------------------------
198 * Gets the error message associated with a particular field
201 * @param string the field name
204 function error($field = '', $prefix = '', $suffix = '')
206 if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
213 $prefix = $this->_error_prefix;
218 $suffix = $this->_error_suffix;
221 return $prefix.$this->_field_data[$field]['error'].$suffix;
224 // --------------------------------------------------------------------
229 * Returns the error messages as a string, wrapped in the error delimiters
236 function error_string($prefix = '', $suffix = '')
238 // No errrors, validation passes!
239 if (count($this->_error_array) === 0)
246 $prefix = $this->_error_prefix;
251 $suffix = $this->_error_suffix;
254 // Generate the error string
256 foreach ($this->_error_array as $val)
260 $str .= $prefix.$val.$suffix."\n";
267 // --------------------------------------------------------------------
272 * This function does all the work.
277 function run($group = '')
279 // Do we even have any data to process? Mm?
280 if (count($_POST) == 0)
285 // Does the _field_data array containing the validation rules exist?
286 // If not, we look to see if they were assigned via a config file
287 if (count($this->_field_data) == 0)
289 // No validation rules? We're done...
290 if (count($this->_config_rules) == 0)
295 // Is there a validation rule for the particular URI being accessed?
296 $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
298 if ($uri != '' AND isset($this->_config_rules[$uri]))
300 $this->set_rules($this->_config_rules[$uri]);
304 $this->set_rules($this->_config_rules);
307 // We're we able to set the rules correctly?
308 if (count($this->_field_data) == 0)
310 log_message('debug', "Unable to find validation rules");
315 // Load the language file containing error messages
316 $this->CI->lang->load('form_validation');
318 // Cycle through the rules for each field, match the
319 // corresponding $_POST item and test for errors
320 foreach ($this->_field_data as $field => $row)
322 // Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
323 // Depending on whether the field name is an array or a string will determine where we get it from.
325 if ($row['is_array'] == TRUE)
327 $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
331 if (isset($_POST[$field]) AND $_POST[$field] != "")
333 $this->_field_data[$field]['postdata'] = $_POST[$field];
337 $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
340 // Did we end up with any errors?
341 $total_errors = count($this->_error_array);
343 if ($total_errors > 0)
345 $this->_safe_form_data = TRUE;
348 // Now we need to re-set the POST data with the new, processed data
349 $this->_reset_post_array();
351 // No errors, validation passes!
352 if ($total_errors == 0)
361 // --------------------------------------------------------------------
364 * Traverse a multidimensional $_POST array index until the data is found
372 function _reduce_array($array, $keys, $i = 0)
374 if (is_array($array))
376 if (isset($keys[$i]))
378 if (isset($array[$keys[$i]]))
380 $array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
396 // --------------------------------------------------------------------
399 * Re-populate the _POST array with our finalized and processed data
404 function _reset_post_array()
406 foreach ($this->_field_data as $field => $row)
408 if ( ! is_null($row['postdata']))
410 if ($row['is_array'] == FALSE)
412 if (isset($_POST[$row['field']]))
414 $_POST[$row['field']] = $this->prep_for_form($row['postdata']);
421 if (count($row['keys']) == 1)
423 $post .= current($row['keys']);
429 foreach ($row['keys'] as $val)
438 $post .= '["'.$val.'"]';
442 if (is_array($row['postdata']))
445 foreach ($row['postdata'] as $k => $v)
447 $array[$k] = $this->prep_for_form($v);
450 $post .= ' = $array;';
454 $post .= ' = "'.$this->prep_for_form($row['postdata']).'";';
463 // --------------------------------------------------------------------
466 * Executes the Validation routines
475 function _execute($row, $rules, $postdata = NULL, $cycles = 0)
477 // If the $_POST data is an array we will run a recursive call
478 if (is_array($postdata))
480 foreach ($postdata as $key => $val)
482 $this->_execute($row, $rules, $val, $cycles);
489 // --------------------------------------------------------------------
491 // If the field is blank, but NOT required, no further tests are necessary
493 if ( ! in_array('required', $rules) AND is_null($postdata))
495 // Before we bail out, does the rule contain a callback?
496 if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
499 $rules = (array('1' => $match[1]));
507 // --------------------------------------------------------------------
509 // Isset Test. Typically this rule will only apply to checkboxes.
510 if (is_null($postdata) AND $callback == FALSE)
512 if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
514 // Set the message type
515 $type = (in_array('required', $rules)) ? 'required' : 'isset';
517 if ( ! isset($this->_error_messages[$type]))
519 if (FALSE === ($line = $this->CI->lang->line($type)))
521 $line = 'The field was not set';
526 $line = $this->_error_messages[$type];
529 // Build the error message
530 $message = sprintf($line, $this->_translate_fieldname($row['label']));
532 // Save the error message
533 $this->_field_data[$row['field']]['error'] = $message;
535 if ( ! isset($this->_error_array[$row['field']]))
537 $this->_error_array[$row['field']] = $message;
544 // --------------------------------------------------------------------
546 // Cycle through each rule and run it
547 foreach ($rules As $rule)
551 // We set the $postdata variable with the current data in our master array so that
552 // each cycle of the loop is dealing with the processed data from the last cycle
553 if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
555 // We shouldn't need this safety, but just in case there isn't an array index
556 // associated with this cycle we'll bail out
557 if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
562 $postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
567 $postdata = $this->_field_data[$row['field']]['postdata'];
570 // --------------------------------------------------------------------
572 // Is the rule a callback?
574 if (substr($rule, 0, 9) == 'callback_')
576 $rule = substr($rule, 9);
580 // Strip the parameter (if exists) from the rule
581 // Rules can contain a parameter: max_length[5]
583 if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
589 // Call the function that corresponds to the rule
590 if ($callback === TRUE)
592 if ( ! method_exists($this->CI, $rule))
597 // Run the function and grab the result
598 $result = $this->CI->$rule($postdata, $param);
600 // Re-assign the result to the master data array
601 if ($_in_array == TRUE)
603 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
607 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
610 // If the field isn't required and we just processed a callback we'll move on...
611 if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
618 if ( ! method_exists($this, $rule))
620 // If our own wrapper function doesn't exist we see if a native PHP function does.
621 // Users can use any native PHP function call that has one param.
622 if (function_exists($rule))
624 $result = $rule($postdata);
626 if ($_in_array == TRUE)
628 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
632 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
639 $result = $this->$rule($postdata, $param);
641 if ($_in_array == TRUE)
643 $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
647 $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
651 // Did the rule test negatively? If so, grab the error.
652 if ($result === FALSE)
654 if ( ! isset($this->_error_messages[$rule]))
656 if (FALSE === ($line = $this->CI->lang->line($rule)))
658 $line = 'Unable to access an error message corresponding to your field name.';
663 $line = $this->_error_messages[$rule];
666 // Build the error message
667 $message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
669 // Save the error message
670 $this->_field_data[$row['field']]['error'] = $message;
672 if ( ! isset($this->_error_array[$row['field']]))
674 $this->_error_array[$row['field']] = $message;
682 // --------------------------------------------------------------------
685 * Translate a field name
688 * @param string the field name
691 function _translate_fieldname($fieldname)
693 // Do we need to translate the field name?
694 // We look for the prefix lang: to determine this
695 if (substr($fieldname, 0, 5) == 'lang:')
698 $line = substr($fieldname, 5);
700 // Were we able to translate the field name? If not we use $line
701 if (FALSE === ($fieldname = $this->CI->lang->line($line)))
710 // --------------------------------------------------------------------
713 * Get the value from a form
715 * Permits you to repopulate a form field with the value it was submitted
716 * with, or, if that value doesn't exist, with the default
719 * @param string the field name
723 function set_value($field = '', $default = '')
725 if ( ! isset($this->_field_data[$field]))
730 return $this->_field_data[$field]['postdata'];
733 // --------------------------------------------------------------------
738 * Enables pull-down lists to be set to the value the user
739 * selected in the event of an error
746 function set_select($field = '', $value = '', $default = FALSE)
748 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
750 if ($default === TRUE AND count($this->_field_data) === 0)
752 return ' selected="selected"';
757 $field = $this->_field_data[$field]['postdata'];
759 if (is_array($field))
761 if ( ! in_array($value, $field))
768 if (($field == '' OR $value == '') OR ($field != $value))
774 return ' selected="selected"';
777 // --------------------------------------------------------------------
782 * Enables radio buttons to be set to the value the user
783 * selected in the event of an error
790 function set_radio($field = '', $value = '', $default = FALSE)
792 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
794 if ($default === TRUE AND count($this->_field_data) === 0)
796 return ' checked="checked"';
801 $field = $this->_field_data[$field]['postdata'];
803 if (is_array($field))
805 if ( ! in_array($value, $field))
812 if (($field == '' OR $value == '') OR ($field != $value))
818 return ' checked="checked"';
821 // --------------------------------------------------------------------
826 * Enables checkboxes to be set to the value the user
827 * selected in the event of an error
834 function set_checkbox($field = '', $value = '', $default = FALSE)
836 if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
838 if ($default === TRUE AND count($this->_field_data) === 0)
840 return ' checked="checked"';
845 $field = $this->_field_data[$field]['postdata'];
847 if (is_array($field))
849 if ( ! in_array($value, $field))
856 if (($field == '' OR $value == '') OR ($field != $value))
862 return ' checked="checked"';
865 // --------------------------------------------------------------------
874 function required($str)
876 if ( ! is_array($str))
878 return (trim($str) == '') ? FALSE : TRUE;
882 return ( ! empty($str));
886 // --------------------------------------------------------------------
889 * Match one field to another
896 function matches($str, $field)
898 if ( ! isset($_POST[$field]))
903 $field = $_POST[$field];
905 return ($str !== $field) ? FALSE : TRUE;
908 // --------------------------------------------------------------------
918 function min_length($str, $val)
920 if (preg_match("/[^0-9]/", $val))
925 if (function_exists('mb_strlen'))
927 return (mb_strlen($str) < $val) ? FALSE : TRUE;
930 return (strlen($str) < $val) ? FALSE : TRUE;
933 // --------------------------------------------------------------------
943 function max_length($str, $val)
945 if (preg_match("/[^0-9]/", $val))
950 if (function_exists('mb_strlen'))
952 return (mb_strlen($str) > $val) ? FALSE : TRUE;
955 return (strlen($str) > $val) ? FALSE : TRUE;
958 // --------------------------------------------------------------------
968 function exact_length($str, $val)
970 if (preg_match("/[^0-9]/", $val))
975 if (function_exists('mb_strlen'))
977 return (mb_strlen($str) != $val) ? FALSE : TRUE;
980 return (strlen($str) != $val) ? FALSE : TRUE;
983 // --------------------------------------------------------------------
992 function valid_email($str)
994 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
997 // --------------------------------------------------------------------
1006 function valid_emails($str)
1008 if (strpos($str, ',') === FALSE)
1010 return $this->valid_email(trim($str));
1013 foreach(explode(',', $str) as $email)
1015 if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
1024 // --------------------------------------------------------------------
1027 * Validate IP Address
1033 function valid_ip($ip)
1035 return $this->CI->input->valid_ip($ip);
1038 // --------------------------------------------------------------------
1047 function alpha($str)
1049 return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
1052 // --------------------------------------------------------------------
1061 function alpha_numeric($str)
1063 return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
1066 // --------------------------------------------------------------------
1069 * Alpha-numeric with underscores and dashes
1075 function alpha_dash($str)
1077 return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
1080 // --------------------------------------------------------------------
1089 function numeric($str)
1091 return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
1095 // --------------------------------------------------------------------
1104 function is_numeric($str)
1106 return ( ! is_numeric($str)) ? FALSE : TRUE;
1109 // --------------------------------------------------------------------
1118 function integer($str)
1120 return (bool)preg_match( '/^[\-+]?[0-9]+$/', $str);
1123 // --------------------------------------------------------------------
1126 * Is a Natural number (0,1,2,3, etc.)
1132 function is_natural($str)
1134 return (bool)preg_match( '/^[0-9]+$/', $str);
1137 // --------------------------------------------------------------------
1140 * Is a Natural number, but not a zero (1,2,3, etc.)
1146 function is_natural_no_zero($str)
1148 if ( ! preg_match( '/^[0-9]+$/', $str))
1161 // --------------------------------------------------------------------
1166 * Tests a string for characters outside of the Base64 alphabet
1167 * as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
1173 function valid_base64($str)
1175 return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
1178 // --------------------------------------------------------------------
1181 * Prep data for form
1183 * This function allows HTML to be safely shown in a form.
1184 * Special characters are converted.
1190 function prep_for_form($data = '')
1192 if (is_array($data))
1194 foreach ($data as $key => $val)
1196 $data[$key] = $this->prep_for_form($val);
1202 if ($this->_safe_form_data == FALSE OR $data === '')
1207 return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
1210 // --------------------------------------------------------------------
1219 function prep_url($str = '')
1221 if ($str == 'http://' OR $str == '')
1226 if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
1228 $str = 'http://'.$str;
1234 // --------------------------------------------------------------------
1243 function strip_image_tags($str)
1245 return $this->CI->input->strip_image_tags($str);
1248 // --------------------------------------------------------------------
1257 function xss_clean($str)
1259 return $this->CI->input->xss_clean($str);
1262 // --------------------------------------------------------------------
1265 * Convert PHP tags to entities
1271 function encode_php_tags($str)
1273 return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
1277 // END Form Validation Class
1279 /* End of file Form_validation.php */
1280 /* Location: ./system/libraries/Form_validation.php */