简体   繁体   English

Laravel 至少一个字段有效

[英]Laravel at least one field is valid

I have an array with two relevant keys where at least one of both shall contain a valid email address.我有一个包含两个相关键的数组,其中至少一个应包含有效的 email 地址。

$data = [
 'mail' => 'firstname.lastname#tld.com',
 'mail2' => 'firstname.lastname@tld.com',
 ...
]

I've tried a validation using the exclude_with method, which works if the mail field is invalid, but mail2 is valid.我尝试使用exclude_with方法进行验证,如果mail字段无效,但mail2有效,则该方法有效。 However, it doesn't vice versa.然而,反之亦然。

$validated = Validator::make($data, [
    'mail' => 'exclude_with:mail|email',
    'mail2' => 'exclude_with:mail2|email',
])->validate();

I could do this easily with other PHP methods or regular expressions, but I wonder if this is archivable with Laravel's validator.我可以使用其他 PHP 方法或正则表达式轻松地做到这一点,但我想知道这是否可以使用 Laravel 的验证器存档。

The goal is to get at least one field with a valid email or fail.目标是至少获得一个具有有效 email 的字段,否则将失败。

Use exclude_unless() in Laravel在 Laravel 中使用exclude_unless()

It was tested with these two examples.用这两个例子进行了测试。 (You can swap array positions too). (您也可以交换数组位置)。 And removed ->validate() as well并删除->validate()以及

  1. One valid and one invalid Email (as per in the question)一个有效,一个无效 Email (根据问题)

     $data = [ 'mail' => 'firstname.lastname#tld.com', // wrong 'mail2' => 'firstname.lastname@tld.com' // correct ]; $validator = Validator::make($data, [ 'mail' => 'exclude_unless:mail2,null|email', 'mail2' => 'exclude_unless:mail,null|email', ]); if ($validator->fails()) { $messages = $validator->messages(); foreach ($messages->all() as $message) { echo $message; } die(); } echo "pass"; die();

    Output was Output 是

    在此处输入图像描述

  2. Both invalid emails两个无效的电子邮件

     $data = [ 'mail' => 'firstname.lastname#tld.com', // wrong 'mail2' => 'firstname.lastname#tld.com' // wrong ]; $validator = Validator::make($data, [ 'mail' => 'exclude_unless:mail2,null|email', 'mail2' => 'exclude_unless:mail,null|email', ]); if ($validator->fails()) { $messages = $validator->messages(); foreach ($messages->all() as $message) { echo $message; } die(); } echo "pass"; die();

    Output Output

    在此处输入图像描述


customize the error message to a standard message such as "At least one Email should be valid" .将错误消息自定义为标准消息,例如“至少一个 Email 应该是有效的”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM