我正在尝试在 lumen 中实现自定义验证规则,并且我正在关注 lumen 5.6 的文档。它说引用laravel验证以查看如何使用验证。我目前正在尝试进行验证以检查该值是否为真 null。所以 $x === ""意味着它失败了这是我创建的 App\Rules 文件夹中的规则。
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class TrueNull implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if($value === "") {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute cannot be an empty string.';
}
}
我直接从 lumen docs 复制了这个,并对 pass 函数进行了修改。在我的模态中有
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use App\Rules\TrueNull;
use Validator;
然后
public function validate($data)
{
// make a new validator object
$v = Validator::make($data,
[
'x' => ['regex:/^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$/', new TrueNull]
]
}
但是对 TrueNull 的验证永远不会发生,因为我错过了连接或真的令人沮丧的事情,因为文档说这应该有效。
这是我的 Controller 调用我正在验证的更新。
public function update(Request $request, $id)
{
/*
In middleware need to add community id to request.
*/
try {
$site = Site::findOrFail($id);
if ($site->validate($request->all())) {
$site->fill($request->all());
// save
$site->save();
} else {
return response()->json($site->errors(), 422);
}
} catch (Exception $e) {
return response()->json($e, 422);
}
return response()->json($site, 200);
}
最佳答案
为了将来引用,我发现了一段随机的代码片段,它抵消了 Lumen 的基本文档。在我为 TrueNull 而不是实现规则的类中,我将其更改为实现 ImplicitRule 并将使用更改为\ImplicitRule 并且它现在发现“”不是空值。
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ImplicitRule;
class TrueNull implements ImplicitRule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if($value === "") {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute cannot be an empty string.';
}
}
关于php - 流明自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558705/