使用自定义规则表单请求



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

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

验证器类

class CustomValidator extends IlluminateValidationValidator{
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识别(或者至少不被执行),因为请求总是成功的。我该怎么解决这个问题?

您打算制定许多自定义规则吗?如果不是(我不相信这个比例很好),以下是我使用的。不是一个漂亮的解决方案,但它很短而且有效:

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

use IlluminateValidationFactory;
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!'
      );
  }
}

最新更新