如果用户名或电子邮件为空,则停止 Laravel 密码验证
Stop Laravel password validation if username or email is empty
我有一个自定义登录表单,它使用 API 验证凭据。一切正常,除了如果我将 username/email 字段留空并输入密码,API 调用仍会在它应该在此之前停止时发送。
我查看了规则 bail
、required_with
(以及其他类似规则),但其中 none 符合要求。
有没有办法只有验证消息:
The identifier field is required.
而不是
The identifier field is required.
Sorry, this is not the password associated with your identifier. Please check and try again.
(如果 username/email 为空则停止密码验证?
控制器代码,按要求(ApiMemberPassword
只是一个自定义规则,发送一个带有用户名和密码的API请求,如果identifier
为空则无用):
$validator = Validator::make($request->all(), [
'identifier' => ['required'],
'password' => ['bail', 'required', new ApiMemberPassword],
]);
由于您没有分享任何代码,因此我的建议是:
- 使用简单的 Javascript 验证字段并仅在两个字段都有值时启用“提交”按钮。
至于只针对email字段返回错误,使用inbuild laravel验证是不可能的。查看线程 here
仅仅是因为,通常为了良好的用户体验,所有关于表单失败的错误都应该一次显示,以便用户可以更正所有错误并在下次提交正确的表单。当它本可以一起完成时,没有必要在 5 次不同的提交上更正用户 5 次。有道理吗?
但是,如果您真的需要这个,您只有两个字段,您可以进行自定义验证以首先检查电子邮件,然后检查密码,或者只需使用 Laravel 内置验证两次。
这样使用:
$this->validate($request, [
'identifier' => 'bail|required',
'password' => ['required', new ApiMemberPassword],
]);
我有一个自定义登录表单,它使用 API 验证凭据。一切正常,除了如果我将 username/email 字段留空并输入密码,API 调用仍会在它应该在此之前停止时发送。
我查看了规则 bail
、required_with
(以及其他类似规则),但其中 none 符合要求。
有没有办法只有验证消息:
The identifier field is required.
而不是
The identifier field is required.
Sorry, this is not the password associated with your identifier. Please check and try again.
(如果 username/email 为空则停止密码验证?
控制器代码,按要求(ApiMemberPassword
只是一个自定义规则,发送一个带有用户名和密码的API请求,如果identifier
为空则无用):
$validator = Validator::make($request->all(), [
'identifier' => ['required'],
'password' => ['bail', 'required', new ApiMemberPassword],
]);
由于您没有分享任何代码,因此我的建议是:
- 使用简单的 Javascript 验证字段并仅在两个字段都有值时启用“提交”按钮。
至于只针对email字段返回错误,使用inbuild laravel验证是不可能的。查看线程 here
仅仅是因为,通常为了良好的用户体验,所有关于表单失败的错误都应该一次显示,以便用户可以更正所有错误并在下次提交正确的表单。当它本可以一起完成时,没有必要在 5 次不同的提交上更正用户 5 次。有道理吗?
但是,如果您真的需要这个,您只有两个字段,您可以进行自定义验证以首先检查电子邮件,然后检查密码,或者只需使用 Laravel 内置验证两次。
这样使用:
$this->validate($request, [
'identifier' => 'bail|required',
'password' => ['required', new ApiMemberPassword],
]);