【问题标题】:validating in cakephp model compare two fields在 cakephp 模型中验证比较两个字段
【发布时间】:2026-01-19 12:20:07
【问题描述】:

我有一个模型 Interesttype 我希望验证两个字段,一个不应该多于另一个,并且不应该小于特定的设置值。这是我的模型。

    class Interesttype extends AppModel
    {
      public $primaryKey = 'int_id';
      public $displayField = 'int_name';
      public $hasMany= array(
            'Loan' => array(
                'className' => 'Loan',
                'foreignKey' => 'lon_int_id'            
            )
        );
      public $validate = array(
            'int_name'=> array(
                    'rule' => 'notEmpty',
                    'allowEmpty' => false,
                    'message' => 'The interest type name is required.'
                    ),
          'int_active'=>array(
                     'rule'=>array('boolean'),
                     'allowEmpty'=>false,
                     'message'=>'Please select the status of this interest type'
                     ),
           'int_max'=> array(
                    'numeric'=>array(
                        'rule' => 'numeric',
                        'allowEmpty' => false,
                        'message' => 'Please specify a valid maximum interest rate.'
                        ),
                    'comparison'=>array(
                        'rule' => array('comparison','>',1000),
                        'allowEmpty' => false,
                        'message' => 'The Maximum interest rate cannot be less than the special rate.'
                        ),
                    'checklimits'=>array(
                        'rule' => array('checkRateLimits','int_min'),
                        'allowEmpty' => false,
                        'message' => 'The Maximum interest rate cannot be less than the minimum rate.'
                        )
                    ),
        'int_min'=> array(
                    'numeric'=>array(
                        'rule' => 'numeric',
                        'allowEmpty' => false,
                        'message' => 'Please specify a valid minimum interest rate.'
                        ),
                    'comparison'=>array(
                        'rule' => array('comparison','>',1000),
                        'allowEmpty' => false,
                        'message' => 'The Minimum interest rate cannot be less than the special rate.'
                        ))
        ); 
   function checkRateLimits($maxr,$minr){
           if($maxr>=$minr){
               return true;
           }
           else{
               return false;
           }
       }
    }

上述模型很好地验证了我的表格,除了不会进行一项检查,它不会检查最高利率是否确实大于或等于最低利率。 我在验证上哪里出错了?

【问题讨论】:

    标签: php validation cakephp


    【解决方案1】:

    您必须添加您的own Validation Method 才能实现此目的。这是一个非常通用的示例,它使用 Validation::comparison() 并支持其所有运算符(><>=<===!=isgreaterisless , greaterorequal, lessorequal, equalto, notequal) 作为 options 数组中的第二个参数和一个用于比较验证值的字段名称作为第三个参数。

    class MyModel extends AppModel
    {
    
        /* Example usage of custom validation function */
        public $validate = array(
            'myfield' => array(
                'lessThanMyOtherField' => array(
                    'rule' => array('comparisonWithField', '<', 'myotherfield'),
                    'message' => 'Myfield value has to be lower then Myotherfield value.',
                ),
            ),
        );
    
        /* Custom validation function */
        public function comparisonWithField($validationFields = array(), $operator = null, $compareFieldName = '') {
            if (!isset($this->data[$this->name][$compareFieldName])) {
                throw new CakeException(sprintf(__('Can\'t compare to the non-existing field "%s" of model %s.'), $compareFieldName, $this->name));
            }
            $compareTo = $this->data[$this->name][$compareFieldName];
            foreach ($validationFields as $key => $value) {
                if (!Validation::comparison($value, $operator, $compareTo)) {
                    return false;
                }
            }
            return true;
        }
    
    }
    

    这是通用的,所以如果你想在你的应用程序的多个模型中使用它,你可以把这个函数扔到你的AppModel 中。您也可以将其设为Behavior,以便在不同模型之间共享。

    【讨论】:

    • 完美运行,这是一个非常通用的功能,谢谢!
    【解决方案2】:

    我不会帮助您编写代码,但我建议您阅读以下支持文章http://bakery.cakephp.org/articles/aranworld/2008/01/14/using-equalto-validation-to-compare-two-form-fields

    <?php   
    class Contact extends AppModel 
    { 
        var $name = 'Contact'; 
        var $validate = array( 
            'email' => array( 
            'identicalFieldValues' => array( 
            'rule' => array('identicalFieldValues', 'confirm_email' ), 
            'message' => 'Please re-enter your password twice so that the values match' 
                    ) 
                ) 
            ); 
    
    
        function identicalFieldValues( $field=array(), $compare_field=null )  
        { 
            foreach( $field as $key => $value ){ 
                $v1 = $value; 
                $v2 = $this->data[$this->name][ $compare_field ];                  
                if($v1 !== $v2) { 
                    return FALSE; 
                } else { 
                    continue; 
                } 
            } 
            return TRUE; 
        } 
    
    } 
    ?>
    

    修改我认为从这里开始应该很容易的代码。

    【讨论】:

      【解决方案3】:

      我认为您无法通过直接将其插入模型中的验证数组来实现这一点。但是,您可以指定自己的验证函数。这里给出一个例子(看模型代码):

      Example custom validation function

      【讨论】:

        【解决方案4】:

        在您的模型中,您的验证应该是字段名称,其中包含指向您要运行的函数的规则。

        并且“不应该小于特定的设定值”我将使用“范围”验证,如下所示。该示例将接受任何大于 0(例如 1)且小于 10 的值

        public $validate = array(
          'maxr'=>array(
            'Rate Limits'=>array(
              'rule'=>'checkRateLimits',
              'message'=>'Your Error Message'
            ),
            'Greater Than'=>array(
              'rule'=>array('range', -1, 11),
              'message'=>'Please enter a number between 0 and 10'
            )
          ),
        );   
        

        在函数中你传递 $data 是被传递的字段。如果 $data 不起作用,请尝试 $this->data['Model']['field'] ex($this->data['Model']['maxr'] >= $this->data['Model ']['minr'])

        function checkRateLimits($data){
          if ( $data['maxr'] >= $data['minr'] ) {
            return true;
          } else {
            $this->invalidate('minr', 'Your error message here');
            return false;
          }
        }
        

        您的表单将类似于

        echo $this->Form->create('Model');
        echo $this->Form->input('maxr');
        echo $this->Form->input('minr');
        echo $this->Form->end('Submit');
        

        【讨论】: