规则对象不触发 passes() 方法
Rule object doesn't fire passes() method
我正在尝试使用规则实施验证以验证模型中的字段;按照官方文档中的说明,是这样的:
1) 在文件夹 App/Rules 我把文件 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) 在我的控制器中class,在方法更新中:
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
}
到目前为止一切顺利,更新数据后出现问题; passes() 方法被完全忽略;并恰好执行更新。这不依赖于方法的逻辑,因为它仍然 returns false 在任何情况下,就像 Laravel 仍然忽略该方法,它没有被执行。
有人可以帮助我吗?
我做错了什么?
如果您正在处理自定义规则 class,它不会验证字段(在您的情况下为 codum)是否为空或不存在于请求中。如果您希望自定义验证对象 运行 即使值为空,您需要使用 ImplicitRule
合同。
同样看到这个article
简而言之,您需要做的是:
class Um implements ImplicitRule
我正在尝试使用规则实施验证以验证模型中的字段;按照官方文档中的说明,是这样的:
1) 在文件夹 App/Rules 我把文件 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) 在我的控制器中class,在方法更新中:
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
}
到目前为止一切顺利,更新数据后出现问题; passes() 方法被完全忽略;并恰好执行更新。这不依赖于方法的逻辑,因为它仍然 returns false 在任何情况下,就像 Laravel 仍然忽略该方法,它没有被执行。
有人可以帮助我吗? 我做错了什么?
如果您正在处理自定义规则 class,它不会验证字段(在您的情况下为 codum)是否为空或不存在于请求中。如果您希望自定义验证对象 运行 即使值为空,您需要使用 ImplicitRule
合同。
同样看到这个article
简而言之,您需要做的是:
class Um implements ImplicitRule