gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:42:28 24 4
gpt4 key购买 nike

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

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

最佳答案

您必须添加您的 own Validation Method使这成为可能。这是一个非常通用的示例,它使用了 Validation::comparison() 并支持其所有运算符( ><>=<===!=isgreaterislessgreaterorequal 6,7 |104| 5, 7 |104| 6,7 |104| , lessorequal ) 作为选项数组中的第二个参数和一个字段名来比较验证值作为第三个参数。

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

}

这是通用的,因此您可以将函数放入 equalto 中如果您想在应用程序的多个模型中使用它。您也可以将其设为 Behavior在不同模型之间共享它。

关于php - 在 cakephp 模型中验证比较两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com