【laravel】validator required_without不起作用,自定义规则

时间:2021-04-09 12:56:58   收藏:0   阅读:0

required_without不起作用,自定义一个规则代替它

想实现的效果: 两个参数二选一,只存在一个返回true,同时存在或同时不存在返回false

使用方式:

$data = [
    ‘fid‘ => 1,
    ‘path‘ => ‘/全部文件/文件夹1‘
];
Validator::make($data, [
    ‘fid‘ => ‘bail|$without:path|numeric‘,
    ‘path‘ => ‘bail|$without:fid|string‘
]);

$without 是自定义规则名,$without:path 表示当 path 不存在时这条规则验证通过

App\Providers\AppServiceProvider 文件的boot方法里定义:

先在文件顶部引入:use Illuminate\Support\Facades\Validator;

Validator::extendImplicit(‘$without‘, function ($attribute, $value, $parameters, $validator) {

      // 被排除的属性是否存在,不存在返回true
      if (!isset($parameters[0])) {
          return true;
      }

      $data = $validator->attributes();  // 待验证的属性数组

      // 当前属性存在且被排除属性不存在
      if (array_key_exists($attribute, $data) && !array_key_exists($parameters[0], $data)) {
          return true;
      }

      // 当前属性不存在,但被排除属性存在
      if (!array_key_exists($attribute, $data) && array_key_exists($parameters[0], $data)) {
          return true;
      }

      $needKey = $attribute;
      $withoutKey = $parameters[0];

      return false;
    });

错误消息占位符替换:

Validator::replacer(‘$without‘, function ($message, $attribute, $rule, $parameters) {

    return str_replace(‘:withoutKey‘, $parameters[0], $message);
      
});

定义错误语言:

resources\lang\xx\validation.php 文件中,第一层数组下添加 :

‘$without‘ => ‘当 :withoutKey 不存在时 :attribute 不能为空。‘

其他:

技术图片

技术图片

技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!