laravel 如何验证 Laravel4 中的选择框输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17235444/
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 08:00:31  来源:igfitidea点击:

How to validate select box input in Laravel4

validationselectinputlaravellaravel-4

提问by eski009

Currently when I want to validate a select box I need to include all the values within the validation field.

目前,当我想验证一个选择框时,我需要在验证字段中包含所有值。

public static $rules = array(
    'type' => array('required', 'in:a,b,c,d')
);

Is there a best practise way to do this using an array?

是否有使用数组执行此操作的最佳实践方法?

For example: I have a long list of country names and want to include this as the validation list. The hacky way of doing this would be something along the lines of:

例如:我有一个很长的国家/地区名称列表,并希望将其作为验证列表包含在内。这样做的hacky方式将是:

public static $rules = array(
    'type' => array('required', 'in:'.implode(',', $countries))
);

Thanks

谢谢

采纳答案by Rob Gordijn

A custom is possible, but a exist-rule can also do the job. More details on http://laravel.com/docs/validation#rule-exists

自定义是可能的,但存在规则也可以完成这项工作。有关http://laravel.com/docs/validation#rule-exists 的更多详细信息

回答by Clem

Create a select menu with an array like so:

创建一个带有数组的选择菜单,如下所示:

$types = [ ''    => 'select a type',
          'one'  => 'type one',
          'a'    => 'type a' ];

And rules for validation like so:

和验证规则如下:

$rules = ['type' => 'required'];

As the first key of $types is an empty string. Will output like this:

因为 $types 的第一个键是一个空字符串。会像这样输出:

 <option value=''>select a type</option>

On validation the required rule will fail validation.

在验证时,所需的规则将无法通过验证。

Assuming all options in the select menu are valid options.

假设选择菜单中的所有选项都是有效选项。