在我的laravel应用程序中,我需要基于条件基础应用验证规则。例如:在Store
方法中,password
字段是必填字段,并且最小字符:6。但是,在Update
方法中,password
字段不是必需字段,如果用户输入密码,则密码必须大于6个字符。
SomeController.php
private function validations($customRules = [])
{
# variables
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'required|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
$messages = [
'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
'contact_person.min' => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',
'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
'mobile_number.numeric' => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',
'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
'email.email' => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',
'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
'pword.min' => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',
'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
];
if(!empty($customRules))
$rules = \array_merge($rules, $customRules);
# returning
return request()->validate($rules, $messages);
}
修改规则后,根据update
方法要求,对pword
字段的最小字符进行验证。由于该字段为空,因此不应发生这种情况。
当前,我被迫这样做。
public function update()
{
...
# validating submitted data
if(!empty(request()->pword))
$this->validations([ 'pword' => 'min:6' ]);
else
$this->validations([ 'pword' => '' ]);
....
}
答案 0 :(得分:1)
您可以使用nullabe
代替required
,如果您使用的是雄辩的话,则空白值会转换为null,因为中间件低于
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
所以您的方法就像
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'nullable|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
}