2

我有一个模型 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;
           }
       }
    }

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

4

4 回答 4

5

您必须添加自己的验证方法才能做到这一点。这是一个非常通用的示例,它使用Validation::comparison()并支持其所有运算符(>, <, >=, <=, ==, !=, isgreater, isless, greaterorequal, lessorequal, equalto, notequal)作为选项数组中的第二个参数和一个用于将验证值与作为第三个参数进行比较的字段名称.

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以在不同模型之间共享它。

于 2014-02-11T17:35:50.580 回答
2

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

<?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; 
    } 

} 
?>

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

于 2013-11-16T02:36:29.877 回答
0

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

示例自定义验证函数

于 2013-09-28T08:40:28.923 回答
-1

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

并且“不应该小于特定的设定值”我将使用“范围”验证,如下所示。该示例将接受大于 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');
于 2013-10-03T19:08:19.977 回答