验证在cakephp模型中比较两个字段 [英] validating in cakephp model compare two fields

查看:131
本文介绍了验证在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'=>'兴趣类型名称是必需的'
),
'int_active'=> array(
'rule'=& ),
'allowEmpty'=> false,
'message'=>'请选择此兴趣类型的状态'
',
'int_max'=> array(
'numeric'=> array(
'rule'=>'numeric',
'allowEmpty'=> false,
'message'=> '请指定有效的最高利率。'
),
'comparison'=> array(
'rule'=> array('comparison','>',1000 ),
'allowEmpty'=> false,
'message'=> '最大利率不能小于特殊利率'
),
'checklimits'=> array(
'rule'=> array('checkRateLimits','int_min '
'allowEmpty'=> false,
'message'=>'最高利率不能低于最低利率'


'int_min'=> array(
'numeric'=> array(
'rule'=>'numeric',
'allowEmpty'=> false,
'message'=> '请指定有效的最低利率。'
),
'comparison'=> array(
'rule'=> array('comparison','>',1000 ),
'allowEmpty'=> false,
'message'=>'最低利率不能低于特殊利率。'
))
);
function checkRateLimits($ maxr,$ minr){
if($ maxr> = $ minr){
return true;
}
else {
return false;
}
}
}

除了不进行一次检查外,它不会检查最高利率是否确实大于或等于最低利率。
我在验证时会出错?

解决方案

您必须添加自己的验证方法,以使其成为可能。以下是一个非常通用的示例,它使用 Validation :: compare() 并支持所有运算符(> < / code>,> = < = == != isgreater code>, moreorequal lessorequal notequal )作为选项数组中的第二个参数,以及用于将验证的值与作为第三个参数进行比较的字段名称。

  class MyModel extends AppModel 
{

/ *自定义验证函数的示例用法* /
public $ validate = array
'myfield'=> array(
'lessThanMyOtherField'=> array(
'rule'=> array('comparisonWithField','<','myotherfield'
'message'=>'Myfield的值必须低于Myotherfield的价值',
),
),
);

/ *自定义验证函数* /
public function comparisonWithField($ validationFields = array(),$ operator = null,$ compareFieldName =''){
if ($ this-> data [$ this-> name] [$ compareFieldName])){
throw new CakeException(sprintf(__('Can\'t比较不存在的字段%s of model%s。'),$ compareFieldName,$ this-> name));
}
$ compareTo = $ this-> data [$ this-> name] [$ compareFieldName];
foreach($ validationFields as $ key => $ value){
if(!Validation :: compare($ value,$ operator,$ compareTo)){
return false;
}
}
return true;
}

}

如果你想在你的应用程序的多个模型中使用它,在 AppModel 中抛出该函数。您也可以将其设为行为,以便在不同型号之间共享。 / p>

I have a model Interesttype where i want two fields to be validated one should not be more than the other and none should be less than a particular set value. Here is my model.

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

the above model validates my forms well except that one check will not be done, it will not check if the maximum interest rate is indeed more than or equal to the minimum inerest rate. Where am i going wrong on the validation?

解决方案

You'll have to add your own Validation Method to make this possible. Here's a pretty generic example that makes use of Validation::comparison() and supports all of its operators (>, <, >=, <=, ==, !=, isgreater, isless, greaterorequal, lessorequal, equalto, notequal) as the second argument in the options array and a field name to compare the validated value to as a third parameter.

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

}

This is generic, so you could throw the function in your AppModel if you want to make use of it in multiple models in your App. You could also make this a Behavior to share it between different models.

这篇关于验证在cakephp模型中比较两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆