简体   繁体   English

Laravel 验证规则:required_without

[英]Laravel Validation rules: required_without

I have two fields: Email and Telephone我有两个字段: EmailTelephone

i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.我想创建一个验证,其中需要两个字段之一,如果设置了一个或两个字段,它应该是正确的格式。

I tried this, but it doesnt work, i need both though我试过这个,但它不起作用,虽然我需要两者

 public static array $createValidationRules = [
        'email' => 'required_without:telephone|email:rfc',
        'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',

    ];

It is correct that both fields produce the required_without error message if both are empty.如果两个字段都为空,则两个字段都会产生required_without错误消息是正确的。 This error message clearly says that the field must be filled if the other is not.此错误消息清楚地表明,如果其他字段没有填写,则必须填写该字段。 You may change the message if needed:如果需要,您可以更改消息:

$messages = [
    'email.required_without' => 'foo',
    'telephone.required_without' => 'bar',
];

However, you must add the nullable rule, so the format rules don't apply when the field is empty:但是,您必须添加nullablenullable规则,因此当字段为空时格式规则不适用:

$rules = [
    'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
    'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];

Furthermore: It is recommended writing the rules as array, especially when using regex .此外:建议将规则编写为数组,尤其是在使用regex

You're using the wrong rule.你使用了错误的规则。 You should use required_with instead of required_without .您应该使用required_with而不是required_without

By docs:通过文档:

required_with - docs required_with -文档

The field under validation must be present and not empty only if any of the other specified fields are present and not empty.

required_without - docs required_without - 文档

The field under validation must be present and not empty only when any of the other specified fields are empty or not present.

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

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