使用 Laravel 验证验证 UUID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46682530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:47:31  来源:igfitidea点击:

Validate UUID with Laravel Validation

phplaravellaravel-5laravel-5.5

提问by rap-2-h

Is there a built-in way to validate UUID with a validation rule? I did not found anything about this in the "Available Validation Rules" documentation.

是否有使用验证规则验证 UUID 的内置方法?我在“可用验证规则”文档中没有找到任何关于此的信息。

回答by Bryse Meijer

Laravel 5.6 provides the ramesey/uuidpackage out of the box now. You can use its "isValid" method now to check for a UUID. I noticed that the regex in the solution above would fail sometimes. I haven't had any issue yet with the package used by Laravel internally.

Laravel 5.6 现在提供了开箱即用的ramesey/uuid包。您现在可以使用其“isValid”方法来检查 UUID。我注意到上面解决方案中的正则表达式有时会失败。我对 Laravel 内部使用的包还没有任何问题。

Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
    return \Ramsey\Uuid\Uuid::isValid($value);
});

Unrelated to the question but you can now also generate a UUID using the "Str" class from Laravel. It is the reason why ramsey/uuid is now included by default, removing the necessity to include your own regex.

与问题无关,但您现在也可以使用 Laravel 的“Str”类生成 UUID。这就是为什么现在默认包含 ramsey/uuid 的原因,消除了包含您自己的正则表达式的必要性。

\Illuminate\Support\Str::uuid();

回答by wshurafa

You can extend the validator helper in Laravel to add your custom validation rules, for example I've created my own validation rule to validate location using regex as follow:

您可以在 Laravel 中扩展验证器助手以添加自定义验证规则,例如我创建了自己的验证规则来使用正则表达式验证位置,如下所示:

Validator::extend('location', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^-?\d{1,2}\.\d{6,}\s*,\s*-?\d{1,2}\.\d{6,}$/', $value);
});

Referencing this post: PHP preg_match UUID v4

参考这篇文章:PHP preg_match UUID v4

You can the use UUID regex to create it as follows:

您可以使用 UUID 正则表达式来创建它,如下所示:

Validator::extend('uuid', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3??}\-[a-f0-9]{12}/', $value);
});

Hope that this match your request.

希望这符合您的要求。

回答by Legionar

Actually, Laravel 5.7 supports UUID validation.

实际上,Laravel 5.7 支持 UUID 验证。

$validation = $this->validate($request, [
    'uuid_field' => 'uuid'
]);

Based on documentation.

基于文档

回答by Murilo Boareto Delefrate

For the ones that are having problem using the validation uuid method in Laravel 5.7, I fixed by updating Laravel (it was 5.7.6 then after updating 5.7.28) and it worked!

对于那些在 Laravel 5.7 中使用验证 uuid 方法有问题的人,我通过更新 Laravel(它是 5.7.6 然后在更新 5.7.28 之后)进行了修复并且它起作用了!

回答by Juha Vehnia

Laravel 5.7 UUID validation is not working for some reason. At least I get

由于某种原因,Laravel 5.7 UUID 验证不起作用。至少我得到

InvalidArgumentException: validation.uuid.

The best way to fix this is to create a rule out of it.

解决此问题的最佳方法是从中创建规则。

php artisan make:rule UUID

Here is my rule class for UUID validation:

这是我用于 UUID 验证的规则类:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Ramsey\Uuid\Uuid as UuidValidator;

class UUID implements Rule
{
    /**
     * Validate UUID
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return UuidValidator::isValid($value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Supplied :attribute is not valid UUID!';
    }
}

Then you can use it manually like this

然后你可以像这样手动使用它

$validator = Validator::make($data->all(), ['uuid' => new UUID]);

if ($validator->fails()) {
     // Do whatever
}

Or use it with http request validation like this

或者像这样使用 http 请求验证

namespace App\Http\Requests;

use App\Rules\UUID;
use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'uuid' => ['required', new UUID],
            'email' => ['required','email']
        ];
    }
}