在cakephp模型中验证比较两个字段

时间:2013-09-26 16:04:22

标签: php validation cakephp

我有一个模型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 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

我不会帮助您完成代码,但我建议您阅读以下背景文章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; 
    } 

} 
?>

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

答案 2 :(得分:0)

我认为你不能直接将它插入到模型中的validate数组中。但是,您可以指定自己的验证功能。这里给出一个例子(看一下模型代码):

Example custom validation function

答案 3 :(得分:-1)

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

并且“None应该小于特定的设定值”我将使用“范围”验证,如下所示。该示例将接受大于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-&gt; data ['Model'] ['field'] ex($ this-&gt; data ['Model'] ['maxr']&gt; = $ this-&gt;数据[ '模型'] [ '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');