流明自定义验证

时间:2018-03-29 14:28:42

标签: php laravel validation 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.';
    }
}

我直接从流明文档复制了这个并修改了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的验证永远不会发生,我错过了一个连接或其真正令人沮丧的东西,因为文档说这应该有效。 这是我的控制器调用我正在验证的更新。

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);
    }

3 个答案:

答案 0 :(得分:2)

为了将来的参考,我发现了一个随机的代码片段来抵消流明的基本文档。在我的TrueNull类而不是实现规则中,我将其更改为实现ImplicitRule并将使用更改为\ ImplicitRule,它现在正在捕获&#34;&#34;不是空的。

<?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.';
    }
}

答案 1 :(得分:2)

Version: Lumen 7.X

首先,在app/Providers/AppServiceProvider.php中声明您的规则。 使用以下规则方法创建boot()(我为电话号码注册了一条规则)。

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默认未在流明中注册。

您需要转到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'
   ]
);

应该的!

答案 2 :(得分:0)

@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',