laravel 验证匹配字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31439203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:57:12  来源:igfitidea点击:

Validating Matching Strings

laravellaravel-5laravel-validation

提问by Neel

When I use the Validation feature in Laravel, how can I add a pre-defined strings that are allowed in an Input?

当我在 Laravel 中使用验证功能时,如何添加允许在输入中使用的预定义字符串?

For example, let's say I want the Input to contain only one of the following: foo,bar,baz, how can I do that?

例如,假设我希望 Input 仅包含以下内容之一:foo,bar,baz,我该怎么做?

$validator = Validator::make($credentials, [
      'profile' => 'required|max:255', // Here I want Predefined allowed values for it
]);

回答by omarjebari

Best to use the 'in' validation rule like this:

最好像这样使用“in”验证规则:

$validator = Validator::make($credentials, [
      'profile' => ["required" , "max:255", "in:foo,bar,baz"]  
]);

回答by ODelibalta

It is recommended in Laravel docs to put the validation rules in an array when they get bigger and I thought 3 rules were sufficient. I think it makes it for a more readable content but you do not have to. I added the regexportion below and I have it works. I am not that great with regexing stuff. Let me know.

Laravel 文档中建议在验证规则变大时将它们放入数组中,我认为 3 条规则就足够了。我认为它使内容更具可读性,但您不必这样做。我添加了regex下面的部分,我有它的工作。我不太擅长正则表达式。让我知道。

$validator = Validator::make($credentials, [
      'profile' => ["required" , "max:255", "regex:(foo|bar|baz)"]  
]);