Laravel有时会验证规则 [英] Laravel sometimes validation rule

查看:438
本文介绍了Laravel有时会验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只尝试验证密码字段(如果存在).我想允许某人编辑用户,他们可能会或可能不想更改用户密码.所以我想我可以使用Laravels验证规则,特别是有时"规则.我有这套规则:

I am trying to validate a password field only if it is present. I want to allow someone to edit a user and they may or may not want to change the users password. So I thought I could this using Laravels validation rules, specifically the 'sometimes' rule. I have this set of rules:

$this->validate($request, [
    'password' => 'sometimes|required|min:8',
]);

为示例进行了简化,通常会有用于其他字段的其他规则,以及用于密码的更严格的规则.我希望这仅在传递的数据中存在密码字段的情况下才应用min:8规则,但是如果我将密码字段保留为空,则会收到验证错误,要求输入密码字段.

This is simplified for the example, there will usually be other rules for other fields and stricter rules for the password. I expect this to only apply the min:8 rule if the password field is present in the passed data, but if I leave the password field empty I get a validation error saying the password field is required.

我不确定我对文档不了解的内容.如果是这样输入的表单输入为空,是否需要在验证之前手动删除密码字段?

I'm not sure what I'm not understanding in the docs. Do I need to manually remove the password field before validation if it is the form input was submitted empty like this?

$data = $request->all();

if ('' === $data['password']) {
    unset($data['password'])
}

...然后将数组传递到验证器.我认为这是有道理的,但我可以做一些确认,以确保我理解正确.预先感谢.

...and then pass the array into the validator. I think this makes sense but I could do with some confirmation that I'm understanding it correctly. Thanks in advance.

推荐答案

文档内容不清楚,但是删除必需的内容即可.

Docs don't make it clear, But removing required makes it work.

$this->validate($request, [
    'password' => 'sometimes|min:8',
]);

这篇关于Laravel有时会验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆