【问题标题】:Form requests with custom rules带有自定义规则的表单请求
【发布时间】:2015-05-28 00:57:28
【问题描述】:

我有一个我想在其中使用自定义规则的 CustomFormRequest。这是 FormRequest 中的 rules() 方法。

public function rules()
{
    return [
            'name' => 'customrule'
    ];
}

Validor 类

class CustomValidator extends Illuminate\Validation\Validator{
protected function customrule( $attribute, $value ) {
    return false;
}

我有一个带有以下 boot() 方法的 CustomServiceProvider

public function boot()
{
   \Validator::resolver(function($translator, $data, $rules, $messages)
    {
         return new CustomValidator($translator, $data, $rules, $messages);
    });
}

CustomServiceProvider 列在 app.php 文件中。

控制器帽子正在使用表单请求

 public function store(CustomFormRequest $request)
{
    $input = $request->all();
    dd("request succeeded");

我的 FormRequest 无法识别此规则(或至少未执行),因为请求始终成功。我该如何解决这个问题?

【问题讨论】:

  • 您可以自己绑定来注册所有新的自定义规则。我已经在这里描述了所有步骤:stackoverflow.com/questions/28417977/…
  • 我更改了代码以实现您的解决方案,但它似乎不起作用:/
  • 如果它不起作用,您需要向我们显示错误
  • 我在函数中返回了一个硬编码的 false,但使用 FormRequest 的控制器中的代码仍在执行。这意味着该函数没有被调用对吗?
  • 向我们展示您调用验证类的控制器部分

标签: validation request laravel-5


【解决方案1】:

您打算制定许多自定义规则吗?如果不是(我不相信这可以很好地扩展),这就是我使用的。不是那么漂亮的解决方案,但它很短并且有效:

在您的请求文件中添加以下内容:

use Illuminate\Validation\Factory;

class YourRequest extends Request {
...

  public function __construct(Factory $factory)
  {
      $factory->extendImplicit('customrule', function ($attribute, $value, $parameters) {
          //$value is what the user typed in the form or what came from POST
          // do some logic here, if the input is correct, return true else return false e.g.:

          if($value == 'what_is_expected')
             return true;
          else
             return false.

      },
          'Custom rule failed error message!'
      );
  }
}

【讨论】:

  • 这可以解决问题。 'someBooleanFunction' 使用在 CustomValidator 中创建的函数(这是正常行为吗?)。使用那个函数似乎有点奇怪。
  • JorenV 没听懂你说的,CustomValidator函数是什么意思? someBooleanFunction 是一个真正的函数吗? O.o
  • 显然不是,看来我对customvalidation的理解不够。我可以注释掉'return booleanfunction',它仍然有效。
  • JorenV 它不存在。你打算验证什么?将您的验证逻辑放在那里而不是函数。 $value 参数是用户输入的,所以检查它是否应该是这样,如果是,则返回 true,如果不是则返回 false。我会编辑答案。
  • 我的意思是,如果我这样写: $factory->extendImplicit('customrule', function ($attribute, $value, $parameters) {},它使用了我的 CustomValidator 的 customrule 函数
猜你喜欢
  • 2017-12-06
  • 2022-08-22
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多