规则对象不会触发pass()方法

时间:2019-02-14 18:11:44

标签: laravel validation rules

我正在尝试使用“规则”实施验证以验证模型中的字段;如官方文档中所示,以这种方式:

1)在“应用程序/规则”文件夹中,我放置了Um.php文件:

<?php
 namespace App\Rules;
 use Illuminate\Contracts\Validation\Rule;
 use App\Models\Common\Item;
 class Um implements Rule
  {

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    if(strlen($attribute) < 5)
    return false;

    return true;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'The field is too short ';
}

}

2)在我的控制器类中,在方法更新中:

 use App\Rules\Um as RuleUm;

...

  public function update(Request $request $item)
{
   //$item is the model don't worry for this 


   //Here is where I invoke the rule 
    $request->validate([
'codum' => [ new RuleUm],
            ]);


    $item->update($request->input());

  //...son on
}

到目前为止,在更新数据后出现问题; pass()方法被完全忽略;并恰好执行更新。这不依赖于方法的逻辑,因为在任何情况下它仍然返回false,就像Laravel仍然忽略该方法一样,它也不会执行。

有人可以帮助我吗? 我在做什么错了?

1 个答案:

答案 0 :(得分:1)

如果您正在使用自定义规则类,它将无法验证该字段(在您的情况下为codum)为空还是在请求中不存在。如果您希望自定义验证对象即使其值为空也可以运行,则需要使用ImplicitRule合同。

请参见此article

简而言之,您需要做:

class Um implements ImplicitRule