php Laravel IN 验证或 ENUM 值验证

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

Laravel IN Validation or Validation by ENUM Values

phpvalidationlaravelenums

提问by Maykonn

I'm initiating in Laravel. I searched and not found how to validate data with some ENUM values. On below code I need that typemust be just DEFAULTor SOCIAL. One or other:

我在 Laravel 中启动。我搜索并没有找到如何使用某些 ENUM 值验证数据。在下面的代码中,我需要的type必须是DEFAULTSOCIAL。一个或另一个:

$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => '', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);

Is possible?

有可能吗?

回答by Alupotha

in:DEFAULT,SOCIAL
The field under validation must be included in the given list of values.

in:DEFAULT,SOCIAL
验证字段必须包含在给定的值列表中。

not_in:DEFAULT,SOCIAL
The field under validation must not be included in the given list of values.

not_in:DEFAULT,SOCIAL
验证中的字段不得包含在给定的值列表中。

$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => 'in:DEFAULT,SOCIAL', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);

:)

:)

回答by Aleksandar

The accepted answer is ok, but I want to add how to set the inrule to use existing constants or array of values.

接受的答案是可以的,但我想添加如何设置in规则以使用现有常量或值数组

So, if You have:

所以,如果你有:

class MyClass {
  const DEFAULT = 'default';
  const SOCIAL = 'social';
  const WHATEVER = 'whatever';
  ...

You can make a validation rule by using Illuminate\Validation\Rule's inmethod:

您可以使用Illuminate\Validation\Rule'sin方法制定验证规则:

'type' => Rule::in([MyClass::DEFAULT, MyClass::SOCIAL, MyClass::WHATEVER])

Or, if You have those values already grouped in an array, You can do:

或者,如果您已经将这些值分组在一个数组中,您可以执行以下操作:

class MyClass {
  const DEFAULT = 'default';
  const SOCIAL = 'social';
  const WHATEVER = 'whatever';
  public static $types = [self::DEFAULT, self::SOCIAL, self::WHATEVER];

and then write the rule as:

然后将规则写为:

'type' => Rule::in(MyClass::$types)