07.18 php saved
wargoth
Tags add more
 
Note
Advanced validation by By Evan Sagge aka "evan", validation.php (should be placed in app/vendors/validation dir).
  1. <?php
  2.  
  3. /**
  4. * Validation class.
  5. *
  6. * This file contaings the validation class for CakePHP.
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * @author      Evan Sagge <evansagge@gmail.com>
  11. * @package     evansagge
  12. * @subpackage  evansagge.cake.model.util
  13. */
  14.  
  15. /**
  16. * Validation class.
  17. *
  18. * This class contains methods for implementing advanced model validation in CakePHP.
  19. * Validation for a field is enabled through the {@link @AppModel::validate} variable.
  20. *
  21. * PHP versions 4 and 5
  22. *
  23. * @author      Evan Sagge <evansagge@gmail.com>
  24. * @package     evansagge
  25. * @subpackage  evansagge.cake
  26. * @see         AppModel
  27. */
  28. class Validation
  29. {
  30.     /**
  31.     * Reference for model data
  32.     */
  33.     var $data;
  34.  
  35.     /**
  36.     * Reference for model object
  37.     */
  38.     var $model;
  39.  
  40.     var $errorCount = 0;
  41.  
  42.     /**
  43.     * Constructor for validation class.  This initializes the data to validate as well as the model
  44.     * against which data should be validated.
  45.     *
  46.     * @param mixed $data The data to validated.
  47.     * @param object $model The model object against which the data should be validated.
  48.     * @return Validation
  49.     */
  50.     function Validation(&$data, &$model)
  51.     {
  52.         $this->data =& $data;
  53.         $this->model =& $model;
  54.         $this->name =& $this->model->name;
  55.     }
  56.  
  57.     /**
  58.     * Evaluates the given validation result.  If the value is set to true, it will return true;
  59.     * otherwise, it has two options: if $params['message'] is defined, it will add its value to
  60.     * the model object's $validationErrors array and return false, else it will add the value of
  61.     * the concatenation of the humanized field name and the passed $messageOnFail string to the
  62.     * model object's $validationErrors array and return false.
  63.     *
  64.     * @param bool $validation The validation result.
  65.     * @param string $messageOnFail The default message to return if the validation results to
  66.     *     false.
  67.     * @param string $fieldName The field name.
  68.     * @param array $params Extra validation parameters.
  69.     * @return Validation
  70.     */
  71.     function _evaluate($validation, $fieldName = null, $params = array())
  72.     {
  73.         if ($validation)
  74.         {
  75.             return true;
  76.         }
  77.  
  78.         $this->model->invalidate($fieldName);
  79.  
  80.         $this->errorCount++;
  81.         return false;
  82.     }
  83.  
  84.     /**
  85.     * Checks if the value defined by the field name is not empty.
  86.     *
  87.     * @param string $fieldName The name of the field to validate.
  88.     * @param array $params Extra validation parameters.
  89.     * @return bool True if value of the field name is not empty; false otherwise.
  90.     */
  91.     function validateNotEmpty($fieldName, $params)
  92.     {
  93.         return $this->_evaluate(!empty($this->data[$this->name][$fieldName]), $fieldName, $params);
  94.     }
  95.  
  96.     /**
  97.     * Alias for Validation::validateNotEmpty()
  98.     */
  99.     function validateRequired($fieldName, $params)
  100.     {
  101.         return $this->_evaluate($this->validateNotEmpty($fieldName, $params), $fieldName, $params);
  102.     }
  103.  
  104.     /**
  105.     * Matches the value defined by the field name against the pattern specified by
  106.     * $params['pattern'].
  107.     *
  108.     * @param string $fieldName The name of the field to validate.
  109.     * @param array $params Contains the pattern to match the value of the field name against.
  110.     * @return bool True if pattern matches the value of the field name; false otherwise.
  111.     */
  112.     function validatePattern($fieldName, $params)
  113.     {
  114.         $pattern = $params['pattern'];
  115.         return $this->_evaluate(preg_match($pattern, $this->data[$this->name][$fieldName]), $fieldName, $params);
  116.     }
  117.  
  118.     /**
  119.     * Checks if the value defined by the field name is a valid word, i.e. contains only
  120.     * alphanumeric characters or the underscore ('_') character.
  121.     *
  122.     * @param string $fieldName The name of the field to validate.
  123.     * @param array $params Extra validation parameters.
  124.     * @return bool True value of the field name is a valid word; false otherwise.
  125.     * @see Validation::validatePattern()
  126.     */
  127.     function validateWord($fieldName, $params)
  128.     {
  129.         $params['pattern'] = '/^\\w*$/';
  130.         return $this->_evaluate($this->validatePattern($fieldName, $params), $fieldName, $params);
  131.     }
  132.  
  133.     /**
  134.     * Checks if the value defined by the field name is an integer.
  135.     *
  136.     * @param string $fieldName The name of the field to validate.
  137.     * @param array $params Extra validation parameters.
  138.     * @return bool True value of the field name is an integer; false otherwise.
  139.     * @see Validation::validatePattern()
  140.     */
  141.     function validateInteger($fieldName, $params)
  142.     {
  143.         $params['pattern'] = '/^\\d+$/';
  144.         return $this->_evaluate($this->validatePattern($fieldName, $params), $fieldName, $params);
  145.     }
  146.  
  147.     /**
  148.     * Checks if the value defined by the field name is a number.
  149.     *
  150.     * @param string $fieldName The name of the field to validate.
  151.     * @param array $params Extra validation parameters.
  152.     * @return bool True value of the field name is a floating point number; false otherwise.
  153.     * @see Validation::validatePattern()
  154.     */
  155.     function validateNumber($fieldName, $params)
  156.     {
  157.         if (isset($params['integerOnly']))
  158.         {
  159.             $params['pattern'] = '/^\\d+$/';
  160.         }
  161.         else
  162.         {
  163.             $params['pattern'] = '/^(\\d+)|(\\d*\.\\d+)$/';
  164.         }
  165.         return $this->_evaluate($this->validatePattern($fieldName, $params), $fieldName, $params);
  166.     }
  167.  
  168.     /**
  169.     * Checks if the value defined by the field name has a valid e-mail address format.
  170.     *
  171.     * @param string $fieldName The name of the field to validate.
  172.     * @param array $params Extra validation parameters.
  173.     * @return bool True if value of the field name has a valid e-mail address format; false
  174.     *      otherwise.
  175.     * @see Validation::validatePattern()
  176.     */
  177.     function validateEmail($fieldName, $params)
  178.     {
  179.         $params['pattern'] = '/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9]'
  180.                 . '[a-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|'
  181.                 . '[a-z]{2,4}))$)\\z/i';
  182.         return $this->_evaluate($this->validatePattern($fieldName, $params), $fieldName, $params);
  183.     }
  184.  
  185.     /**
  186.     * Checks if the value defined by the field name is a valid value for a year.
  187.     *
  188.     * @param string $fieldName The name of the field to validate.
  189.     * @param array $params Extra validation parameters.
  190.     * @return bool True if value of the field name is a valid value for a year; false
  191.     *      otherwise.
  192.     * @see Validation::validatePattern()
  193.     */
  194.     function validateYear($fieldName)
  195.     {
  196.         $params['pattern'] = '/^[12][0-9]{3}$/';
  197.         return $this->_evaluate($this->validatePattern($fieldName, $params), $fieldName, $params);
  198.     }
  199.  
  200.     /**
  201.     * Checks if the value defined by the field name is unique for the given data model.  The
  202.     *      check for uniqueness is case-insensitive.  If $params['conditions'] is given,
  203.     *      this is used as a constraint.  If $params['scope'] is given, the value of
  204.     *      the field name is only checked against records that match the value of the
  205.     *      column/field defined by $params['scope'].
  206.     *
  207.     * @param string $fieldName The name of the field to validate.
  208.     * @param array $params Extra validation parameters.
  209.     * @return bool True if value of the field name is unique; false otherwise.
  210.     * @see Model::hasAny()
  211.     */
  212.     function validateUnique($fieldName, $params)
  213.     {
  214.         $val = $this->data[$this->name][$fieldName];
  215.         $column = $this->name . '.' . $fieldName;
  216.         $id = $this->name . '.' . $this->model->primaryKey;
  217.  
  218.         $conditions = array();
  219.         if (isset($params['conditions']))
  220.         {
  221.             $conditions = $params['conditions'];
  222.         }
  223.  
  224.         if (isset($params['scope']))
  225.         {
  226.             if (is_array($params['scope']))
  227.             {
  228.                 foreach ($params['scope'] as $scope)
  229.                 {
  230.                     $conditions[$scope] = $this->data[$this->name][$scope];
  231.                 }
  232.             }
  233.             else if (is_string($params['scope']))
  234.             {
  235.                 $conditions[$params['scope']] = $this->data[$this->name][$params['scope']];
  236.             }
  237.         }
  238.  
  239.         $conditions[$column] = $val;
  240.         if (!empty($this->data[$this->name][$this->model->primaryKey]))
  241.         {
  242.             $conditions[$id] = ('!=' . $this->data[$this->name][$this->model->primaryKey]);
  243.         }
  244.  
  245.         return $this->_evaluate(!$this->model->hasAny($conditions), $fieldName, $params);
  246.     }
  247.  
  248.     /**
  249.     * Checks if the length of the string value defined by the field name is within the range
  250.     *      specified by $params['min'], $params['max'], or both.
  251.     *
  252.     * @param string $fieldName The name of the field to validate.
  253.     * @param array $params Extra validation parameters.
  254.     * @return bool True if length of the value of the field name is within the specified range;
  255.     *      false otherwise.
  256.     */
  257.     function validateLength($fieldName, $params)
  258.     {
  259.         $val = $this->data[$this->name][$fieldName];
  260.         $length = strlen($val);
  261.  
  262.         if (array_key_exists('min', $params) && array_key_exists('max', $params))
  263.         {
  264.             return $this->_evaluate($length >= $params['min'] && $length <= $params['max'], $fieldName, $params);
  265.         }
  266.         else if (array_key_exists('min', $params))
  267.         {
  268.             return $this->_evaluate($length >= $params['min'], $fieldName, $params);
  269.         }
  270.         else if (array_key_exists('max', $params))
  271.         {
  272.             return $this->_evaluate($length <= $params['max'], $fieldName, $params);
  273.         }
  274.     }
  275.  
  276.     /**
  277.     * Checks if the numeric value defined by the field name is within the range
  278.     *      specified by $params['min'], $params['max'], or both.
  279.     *
  280.     * @param string $fieldName The name of the field to validate.
  281.     * @param array $params Extra validation parameters.
  282.     * @return bool True if numeric value of the field name is within the specified range;
  283.     *      false otherwise.
  284.     */
  285.     function validateRange($fieldName, $params)
  286.     {
  287.         if ($result = $this->validateNumber($fieldName, $params))
  288.         {
  289.             return $result;
  290.         }
  291.  
  292.         $val = $this->data[$this->name][$fieldName];
  293.  
  294.         if (array_key_exists('min', $params) && array_key_exists('max', $params))
  295.         {
  296.             return $this->_evaluate($val >= $params['min'] && $val <= $params['max'], $fieldName, $params);
  297.         }
  298.         else if (array_key_exists('min', $params))
  299.         {
  300.             return $this->_evaluate($val >= $params['min'], $fieldName, $params);
  301.         }
  302.         else if (array_key_exists('max', $params))
  303.         {
  304.             return $this->_evaluate($val <= $params['max'], $fieldName, $params);
  305.         }
  306.     }
  307.  
  308.     /**
  309.     * Checks if the value defined by the field name corresponds with it's confirmation value,
  310.     *      which is defined by the field specified in {@link $params}['confirm_var'] if defined,
  311.     *      or by <the field name>_confirmation.
  312.     *
  313.     * @param string $fieldName The name of the field to validate.
  314.     * @param array $params Extra validation parameters.
  315.     * @return bool True if value of the field name corresponds to its confirmation
  316.     *      value; false otherwise.
  317.     */
  318.     function validateConfirmed($fieldName, $params)
  319.     {
  320.         $val = $this->data[$this->name][$fieldName];
  321.  
  322.         if (array_key_exists('confirm_var', $params))
  323.         {
  324.             $confirmVar = $params['confirm_var'];
  325.         }
  326.         else
  327.         {
  328.             if (empty($this->data[$this->name][$fieldName . '_confirmation']))
  329.             {
  330.                 $returnValue = false;
  331.             }
  332.             $confirmVar = $fieldName . '_confirmation';
  333.         }
  334.  
  335.         if (empty($this->data[$this->name][$confirmVar]))
  336.         {
  337.             $this->data[$this->name][$confirmVar] = null;
  338.         }
  339.  
  340.         return $this->_evaluate($val == $this->data[$this->name][$confirmVar], $fieldName, $params);
  341.     }
  342.  
  343.     /**
  344.     * Checks if the value defined by the field name is a file.
  345.     *
  346.     * @param string $fieldName The name of the field to validate.
  347.     * @param array $params Extra validation parameters.
  348.     * @return bool True if value of the field name is a file; false otherwise.
  349.     */
  350.     function validateFile($fieldName, $params)
  351.     {
  352.         $file = $this->data[$this->name][$fieldName];
  353.  
  354.         $returnValue = true;
  355.  
  356.         if ($file['error'] == UPLOAD_ERR_OK)
  357.         {
  358.             if (isset($params['allowedTypes']) && !in_array($file['type'], $params['allowedTypes']))
  359.             {
  360.                 $returnValue = false;
  361.             }
  362.         }
  363.         else
  364.         {
  365.             unset($this->data[$this->name][$fieldName]);
  366.         }
  367.  
  368.         return $this->_evaluate($returnValue, $fieldName, $params);
  369.     }
  370.  
  371.     /**
  372.     * Checks if the value defined by the field name is an image file.
  373.     *
  374.     * @param string $fieldName The name of the field to validate.
  375.     * @param array $params Extra validation parameters.
  376.     * @return bool True if value of the field name is an image file; false otherwise.
  377.     * @see Validation::validateFile()
  378.     */
  379.     function validateImageFile($fieldName, $params)
  380.     {
  381.         $params['allowedTypes'] = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png',
  382.                 'image/x-png', 'image/x-jg', 'image/gif');
  383.  
  384.         return $this->_evaluate($this->validateFile($fieldName, $params), $fieldName, $params);
  385.     }
  386.  
  387.     /**
  388.     * Checks if the value defined by the field name is a properly uploaded file.
  389.     *
  390.     * @param string $fieldName The name of the field to validate.
  391.     * @param array $params Extra validation parameters.
  392.     * @return bool True if value of the field name is a properly uploaded file; false otherwise.
  393.     */
  394.     function validateUploaded($fieldName, $params)
  395.     {
  396.         return $this->_evaluate(is_uploaded_file($this->data[$this->name][$fieldName]['tmp_name']), $fieldName, $params);
  397.     }
  398.  
  399.     /**
  400.     * Checks if the value defined by the field name is a date set in the future.  This
  401.     * automatically checks if the value is in proper date format.
  402.     *
  403.     * @param string $fieldName The name of the field to validate.
  404.     * @param array $params Extra validation parameters.
  405.     * @return bool True if value of the field name is a future date; false otherwise.
  406.     * @see Validation::validateDate()
  407.     */
  408.     function validateFutureDate($fieldName, $params)
  409.     {
  410.         if ($result = $this->validateDate($fieldName, $params))
  411.         {
  412.             return $result;
  413.         }
  414.  
  415.         $date = strtotime($this->data[$this->name][$fieldName]);
  416.  
  417.         return $this->_evaluate($date > time(), $fieldName, $params);
  418.     }
  419.  
  420.     /**
  421.     * Checks if the value defined by the field name is in proper date format (yyyy-mm-dd).
  422.     *
  423.     * @param string $fieldName The name of the field to validate.
  424.     * @param array $params Extra validation parameters.
  425.     * @return bool True if value of the field name is in proper date format; false otherwise.
  426.     */
  427.     function validateDate($fieldName, $params)
  428.     {
  429.         $date = $this->data[$this->name][$fieldName];
  430.  
  431.         $datePattern = '/^\d{4}-\d?\d-\d?\d$/';
  432.         if ($date && preg_match($datePattern, $date))
  433.         {
  434.             $date = explode('-',$date);
  435.             $result = checkdate($date[1], $date[2], $date[0]);
  436.         }
  437.         else
  438.         {
  439.             $result = false;
  440.         }
  441.  
  442.         return $this->_evaluate($result, $fieldName, $params);
  443.     }
  444.  
  445.     /**
  446.     * Checks if the value defined by the field name is in proper datetime format
  447.     * (yyyy-mm-dd HH:MM:SS).
  448.     *
  449.     * @param string $fieldName The name of the field to validate.
  450.     * @param array $params Extra validation parameters.
  451.     * @return bool True if value of the field name is in proper datetime format; false otherwise.
  452.     */
  453.     function validateDatetime($fieldName, $params)
  454.     {
  455.         $dateTime = $this->data[$this->name][$fieldName];
  456.  
  457.         $dateTimePattern = '/^\d{4}-\d?\d-\d?\d '
  458.                 . '([01]?[0-9]|[2][0-4]):([0-5]?[0-9]):([0-5]?[0-9])$/';
  459.  
  460.         if ($dateTime && preg_match($dateTimePattern, $dateTime))
  461.         {
  462.             list($date, $time) = explode(' ', $dateTime);
  463.             $date = explode('-',$date);
  464.             $result = checkdate($date[1], $date[2], $date[0]);
  465.         }
  466.         else
  467.         {
  468.             $result = false;
  469.         }
  470.  
  471.         return $this->_evaluate($result, $fieldName, $params);
  472.     }
  473.  
  474.     /**
  475.     * Runs a method in the model object, passing to it the value of the specified field and the
  476.     * additional parameters.  The method's name is checked from the value of $params['method']; if
  477.     * this is not available, then this function will try to call validate{Fieldname} instead.  If
  478.     * the method call fails, this function will return false.
  479.     *
  480.     * @param string $fieldName The name of the field to validate.
  481.     * @param array $params Extra validation parameters.
  482.     * @return bool True if value of the field name is in proper datetime format; false otherwise.
  483.     */
  484.     function validateMethod($fieldName, $params)
  485.     {
  486.         $method = isset($params['method']) ? $params['method'] : 'validate'
  487.                 . Inflector::humanize($fieldName);
  488.  
  489.         if (!method_exists($this->model, $method))
  490.         {
  491.             $this->errorCount++;
  492.             return false;
  493.         }
  494.         else
  495.         {
  496.             if (call_user_func(array(&$this->model, $method), $this->data[$this->name][$fieldName],
  497.                     $params))
  498.             {
  499.                 return true;
  500.             }
  501.             else
  502.             {
  503.                 $this->errorCount++;
  504.                 return false;
  505.             }
  506.         }
  507.  
  508.     }
  509.  
  510. }
Parsed in 0.436 seconds, using GeSHi 1.0.7.14

Modify this Paste