在我的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' => '' ]);
....
}
首先从pword
中删除rules
,然后再将$request->password
传递给validations
方法,否则,$request
会更好,以便将来进行更多的条件检查
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
....
....
if(!$update){
$rules['pword'] = 'required|min:6';
}else if($update && $request->password){
$rules['pword'] = 'min:6';
}
}