我正在尝试使用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',
]);
尝试使用nullable作为规则
'password' => 'nullable|min:6|confirmed',
见https://laravel.com/docs/5.4/validation#a-note-on-optional-fields
'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
根据密码字段创建规则。仅在存在密码字段时才进行验证。
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);
我就是这样做的:
//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
]);
说明: 这样,只有在请求中定义(存在)时才会验证该值 如果使用nullable,则验证器将接受null作为值(我认为这是不可接受的) 如果从更新中删除密码验证,则根本不会验证此输入,并且将接受任何值(这也是不可接受的);