gpt4 book ai didi

laravel - Laravel 第一次失败后如何停止所有验证?

转载 作者:行者123 更新时间:2023-12-03 17:14:50 25 4
gpt4 key购买 nike

有一个函数叫 bail 在 Laravel 中,失败时停止验证。如果我想在第一次失败时停止所有验证怎么办?

例如:

$request->validate([
'antibotprotection' => 'bail|required|exists:protectioncodes,protection_code|max:255',
'email' => 'required|string|email|max:255|unique:users',
]);

此代码将停止验证 antibotprotection但随后它将继续验证电子邮件并传递错误以查看电子邮件,这与整个目的背道而驰。我该如何阻止这一切 validate第一次失败时的功能?

最佳答案

./app/Validation/BailingValidator.php

<?php

namespace App\Validation;

use Illuminate\Support\MessageBag;
use Illuminate\Validation\Validator;

class BailingValidator extends Validator
{
/**
* Determine if the data passes the validation rules.
*
* @return bool
*/
public function passes()
{
$this->messages = new MessageBag;

// We'll spin through each rule, validating the attributes attached to that
// rule. Any error messages will be added to the containers with each of
// the other error messages, returning true if we don't have messages.
foreach ($this->rules as $attribute => $rules) {
$attribute = str_replace('\.', '->', $attribute);

foreach ($rules as $rule) {
$this->validateAttribute($attribute, $rule);

if ($this->shouldStopValidating($attribute)) {
break 2;
}
}
}

// Here we will spin through all of the "after" hooks on this validator and
// fire them off. This gives the callbacks a chance to perform all kinds
// of other validation that needs to get wrapped up in this operation.
foreach ($this->after as $after) {
call_user_func($after);
}

return $this->messages->isEmpty();
}
}
./app/Providers/AppServiceProvider.php
...
use App\Validation\BailingValidator;
use Illuminate\Contracts\Translation\Translator;
use Illuminate\Contracts\Validation\Factory;
use Illuminate\Support\ServiceProvider;
...
public function boot()
{
/**
* @var \Illuminate\Validation\Factory $factory
*/
$factory = resolve(Factory::class);

$factory->resolver(function (Translator $translator, array $data, array $rules, array $messages, array $customAttributes) {
return new BailingValidator($translator, $data, $rules, $messages, $customAttributes);
});
}
...
./app/Http/Controller/SomeController.php
...
$this->validate($request, [
'foo' => ['bail', 'required'],
'bar' => ['bail', 'required'],
]);
...
{"message":"The given data was invalid.","errors":{"foo":["The foo field is required."]}}

关于laravel - Laravel 第一次失败后如何停止所有验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51871722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com