流明自定义验证
Lumen Custom Validation
我正在尝试在 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 文档中复制了这个,并对 passes 函数进行了修改。在我的模式中有
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 的验证永远不会发生,我错过了一个连接或它真的令人沮丧,因为文档说这应该有效。
这是我的控制器调用我正在验证的更新。
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 的基本文档。在我的 class for TrueNull 而不是 implements Rule 中,我将其更改为 implements ImplicitRule 并将 use 更改为 \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.';
}
}
@Alexander Beyers 给出了答案,但它不适用于 Lumen 5.3。以下是如何为 Lumen 5.3 创建有组织的自定义规则。
在应用程序目录下创建目录名称规则并创建以下文件:
namespace App\Rules;
use Illuminate\Support\Facades\Validator;
class AlphaSpace
{
public static function validate(){
//Extending the custom validation rule.
Validator::extend('alpha_spaces', function ($attribute, $value) {
// This will only accept alpha and spaces.
// If you want to accept hyphens use: /^[\pL\s-]+$/u.
return preg_match('/^[\pL\s]+$/u', $value);
});
}
}
打开文件 resources/lang/en/validation
并在自定义验证下添加以下内容:
注意:(自定义验证下仅用于维护)
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'alpha_spaces' => 'The :attribute may only contain letters and spaces.',
调用app/Providers/AppServiceProvider::boot():
中的规则
use HRM\Core\Rules\AlphaSpace;
class AppServiceProvider extends ServiceProvider
{
public function boot() {
AlphaSpace::validate();
}
// class will carry on with the stuffs!
现在您可以在任何您喜欢的地方使用它:
'first_name' => 'required|alpha_spaces|min:3|max:50',
'last_name' => 'required|alpha_spaces|min:3|max:50',
Version: Lumen 7.X
首先,在 app/Providers/AppServiceProvider.php
中声明您的规则。
使用您的规则方法创建一个 boot()
,如下所示(我为 phone 号码注册了一个规则)。
public function register()
{
//
}
public function boot()
{
app('validator')->extend('phone', function ($attribute, $value) {
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\/]?){0,})(?:[\-\.\ \\/]?(?:#|ext\.?|extension|x)[\-\.\ \\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
});
app('validator')->replacer('phone', function ($message, $attribute, $rule, $parameters) {
return 'Phone number has wrong format.';
});
}
与Laravel相反的不同部分,最重要的是,AppServiceProvider
默认情况下未在Lumen中注册。
您需要转到 bootstrap/app.php
并取消注释以下行:
$app->register(App\Providers\AppServiceProvider::class);
也许你想做 composer dumpautoload
,以防万一,但没有它应该也能工作。
然后,在您的代码中:
$validator = Validator::make(
$request->all(),
[
'tel' => 'required|phone'
],
[
'tel.required' => 'Phone is required',
'tel.phone' => 'Phone has wrong format'
]
);
应该就是了!
我正在尝试在 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 文档中复制了这个,并对 passes 函数进行了修改。在我的模式中有
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 的验证永远不会发生,我错过了一个连接或它真的令人沮丧,因为文档说这应该有效。 这是我的控制器调用我正在验证的更新。
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 的基本文档。在我的 class for TrueNull 而不是 implements Rule 中,我将其更改为 implements ImplicitRule 并将 use 更改为 \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.';
}
}
@Alexander Beyers 给出了答案,但它不适用于 Lumen 5.3。以下是如何为 Lumen 5.3 创建有组织的自定义规则。
在应用程序目录下创建目录名称规则并创建以下文件:
namespace App\Rules;
use Illuminate\Support\Facades\Validator;
class AlphaSpace
{
public static function validate(){
//Extending the custom validation rule.
Validator::extend('alpha_spaces', function ($attribute, $value) {
// This will only accept alpha and spaces.
// If you want to accept hyphens use: /^[\pL\s-]+$/u.
return preg_match('/^[\pL\s]+$/u', $value);
});
}
}
打开文件 resources/lang/en/validation
并在自定义验证下添加以下内容:
注意:(自定义验证下仅用于维护)
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'alpha_spaces' => 'The :attribute may only contain letters and spaces.',
调用app/Providers/AppServiceProvider::boot():
中的规则use HRM\Core\Rules\AlphaSpace;
class AppServiceProvider extends ServiceProvider
{
public function boot() {
AlphaSpace::validate();
}
// class will carry on with the stuffs!
现在您可以在任何您喜欢的地方使用它:
'first_name' => 'required|alpha_spaces|min:3|max:50',
'last_name' => 'required|alpha_spaces|min:3|max:50',
Version: Lumen 7.X
首先,在 app/Providers/AppServiceProvider.php
中声明您的规则。
使用您的规则方法创建一个 boot()
,如下所示(我为 phone 号码注册了一个规则)。
public function register()
{
//
}
public function boot()
{
app('validator')->extend('phone', function ($attribute, $value) {
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\/]?){0,})(?:[\-\.\ \\/]?(?:#|ext\.?|extension|x)[\-\.\ \\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
});
app('validator')->replacer('phone', function ($message, $attribute, $rule, $parameters) {
return 'Phone number has wrong format.';
});
}
与Laravel相反的不同部分,最重要的是,AppServiceProvider
默认情况下未在Lumen中注册。
您需要转到 bootstrap/app.php
并取消注释以下行:
$app->register(App\Providers\AppServiceProvider::class);
也许你想做 composer dumpautoload
,以防万一,但没有它应该也能工作。
然后,在您的代码中:
$validator = Validator::make(
$request->all(),
[
'tel' => 'required|phone'
],
[
'tel.required' => 'Phone is required',
'tel.phone' => 'Phone has wrong format'
]
);
应该就是了!