【问题标题】:Cakephp Custom Validation Method Returning False but Saves and Displays no MessageCakephp 自定义验证方法返回 False 但保存并不显示任何消息
【发布时间】:2020-12-17 16:51:14
【问题描述】:

我在 ValidationDefault 下有以下验证器来检查 effective_until 日期是否在 Effective_on 日期之后。如果为 false,则应显示消息。

$validator
            ->add('effective_until', 'custom', ['rule' => 'checkEffectiveDateRange', 'provider' => 'table', 'message' => 'The effective until date must come after the effective on date.']);

我在同一个表中有以下自定义函数,但即使我故意将 effective_until 日期设置为早于 Effective_on 日期,它也会保存数据并且不显示验证错误消息。我在这里做错了吗?

    public function checkEffectiveDateRange($check, $context)
    {
        if(array_key_exists('newRecord',$context))
        {
                return strtotime($context['data']['effective_on']) < strtotime($check);
        }
        else
        {
                return strtotime($context['effective_on']) < strtotime($check);
        }
    }

【问题讨论】:

  • 没有足够的数据在这里提供答案,但考虑使用匿名函数作为验证方法:` $validator ->add('effective_until', 'custom', [ 'on' => ' create', 'rule' => function ($check, $context) { if(array_key_exists...) { return strtotime... __('验证信息...') ]); `
  • 需要哪些额外数据才能提供?匿名函数是唯一的选择吗?在版本 3 中,这与我的表函数一起使用,但现在它似乎无法识别我用于验证的任何表函数。这是 3 个中的一个,它们都不起作用。

标签: validation cakephp cakephp-4.x


【解决方案1】:

对于可能需要此功能的任何人,我通过将验证器更改为以下解决了此问题

验证器

public function validationDefault(Validator $validator): Validator
{
        $validator
            ->add('effective_until', 'custom',
            ['rule' => function($check, $context) {
                if($this->checkEffectiveDateRange($check, $context)) {
                        return true;
                }
                return false;
            },
            'message' => 'The effective until date must come after the effective on date.']);

        return $validator;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多