我正在为两个字段(URL和附件字段)创建自定义验证。我试图验证两个字段都只需要一个字段,但是当用户同时填写两个字段时,他只能填写任何一个字段都会出错。
为此,我在AppServiceProvider.php中做到了:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('empty_if', function($attribute, $value, $parameters, $validator) {
$fields = $validator->getData(); //data passed to your validator
foreach($parameters as $param) {
$excludeValue = array_get($fields, $param, false);
// dd($excludeValue);
if($excludeValue) { //if exclude value is present validation not passed
return true;
}
}
return true;
});
Validator::replacer('empty_if', function($message, $attribute, $rule, $parameters){
$replace = [$attribute, $parameters[0]];
$message = "The field :attribute cannot be filled if :other is also filled";
return str_replace([':attribute', ':other'], $replace, $message);
});
}
}
以及在我的控制器中:
public function createFile(Request $request){
$this->validate($request,[
'url' => 'empty_if:attachment|url|URL|string',
'attachment' => 'empty_if:url|attachment',
'attachment.*' => 'mimes:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt,csv|max:1999',
'client' => 'required|string',
'projectTask' => 'required',
]);
}
提交表单时出现此错误:
message: Method Illuminate\Validation\Validator::validateAttachment does not exist.
exception: BadMethodCallException
请告诉我,extend()的逻辑中是否有任何错误。我在哪里做错了,所以我得到了这个错误。在此先感谢
答案 0 :(得分:0)
您的问题是这一行:
'attachment' => 'empty_if:url|attachment',
这里说要使用attachment
规则和(不存在的)empty_if:url
规则来验证attachment
字段。