我正在尝试使用laravel 5.4
创建和更新用户这是为创建用户添加的验证。它有效。
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
在更新时,不需要密码字段。但是如果密码字段不为空,则验证min:6并确认规则。试过sometimes
..但没有工作..
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,'.$id,
'password' => 'sometimes|min:6|confirmed',
]);
答案 0 :(得分:21)
尝试使用nullable作为规则
'password' => 'nullable|min:6|confirmed',
请参阅https://laravel.com/docs/5.4/validation#a-note-on-optional-fields
答案 1 :(得分:1)
'password' => 'nullable|min:6|confirmed',
@Rejinderi的答案是正确的!
'password' => 'sometimes|required|min:6|confirmed',
username = 'admin',
password = null // fail- required
username = 'admin',
password = 123 // fail- min:6
username = 'admin' // pass- validate only exist
答案 2 :(得分:0)
根据密码字段创建规则。仅在存在密码字段时才进行验证。
if ($request->input('password')) {
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,'.$id,
'password' => 'required|min:6|confirmed',
];
} else {
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,'.$id
];
}
$this->validate($request, $rules);
答案 3 :(得分:0)
我就是这样做的:
//For new or create :
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
//For edit or update:
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'min:6|confirmed',//just remove required from password rule
]);
<强>解释强>
这样,只有在请求中定义(存在)时,才会验证该值
如果您使用可以为空的,则验证者将接受 null 作为值(我认为这是不可接受的)
如果您从更新中删除密码验证,则此输入将完全无法验证,并且任何值将被接受(这也是不可接受的);