我正在 CakePHP 上开发一个应用程序,但我是数据验证的新手。 我需要的是在修改字段时检查日期时间值,因此我需要检查旧的日期时间值并验证新的日期时间值是否等于或更高。 我认为最好是使用自定义验证,但不知道如何获取字段的旧值,以及如何区分创建和编辑。
这里是一个简单的例子:
1)我在数据库中注册一个新事件,它有名称、开始日期、结束日期、ecc...
2)我想编辑此事件,因此我插入一个新的开始日期和一个新的结束日期,现在我需要此验证:
如果旧的最终值在新的之前:
更新记录;
其他:
数据验证失败,不更新记录;
最佳答案
数据验证在您的模型中进行(如果您确实愿意,可以在 Controller 中完成,但如果在模型中完成,Cake 会使事情变得更容易)。
在您的“事件”模型中:
$public validate = array( //each field can have its own validation rule set here
'end_date' => array(
'rule' => 'customEndDateValidation', //the name of our custom validation function to use
'on' => 'update', //only do this when we update a record
'message' => 'New end date must be greater than previous end date' //message if validation fails
)
);
public function customEndDateValidation($check) {
//get previous end date
$old_record = $this->find(
'all',
array(
'conditions' => array(
'Event.id' => $this->data[$this->alias]['id']
),
'fields' => array(
'Event.end_date'
)
)
);
//if the new end date is greater than the old one return true - otherwise it will reach the return false
if (strtotime($check['end_date']) > strtotime($old_record['Event']['end_date'])) {
return TRUE;
}
return FALSE;
}
有关 Cake 中验证的更多信息,请参阅 http://book.cakephp.org/2.0/en/models/data-validation.html
关于php - 使用旧字段值进行数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010784/