laravel 如何验证是否等于变量

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

laravel how to validate as equal to a variable

laravelvalidationlaravel-5laravel-5.4laravel-validation

提问by K1-Aria

in laravel validation (registering) i want to compare one of the fields with a php variable (it should be equal with that)

在 Laravel 验证(注册)中,我想将其中一个字段与一个 php 变量进行比较(它应该与那个相同)

how can i do this?

我怎样才能做到这一点?

protected function validator(array $data)
{

    return Validator::make($data, [
        'name' => 'required|max:255',
        'phone' => 'required|min:10|max:11|unique:users',
        'email' => 'required|email|max:255',
        'password' => 'required',
        'password_confirmation' => 'required',
        'user_captcha' => 'required'
    ]);
}

回答by Leonardo Cabré

You can do it for example for name field like this:

例如,您可以为这样的名称字段执行此操作:

$variable = "something"
return Validator::make($data, [
    'name' => [
        'required',
        Rule::in([$variable]),
    ],
    'phone' => 'required|min:10|max:11|unique:users',
    'email' => 'required|email|max:255',
    'password' => 'required',
    'password_confirmation' => 'required',
    'user_captcha' => 'required'
]);

Remember to import Rule Class (use Illuminate\Validation\Rule;)

记得导入规则类(使用 Illuminate\Validation\Rule;)

You can get more info in: https://laravel.com/docs/5.4/validation#rule-in

您可以在以下位置获取更多信息:https: //laravel.com/docs/5.4/validation#rule-in

EDIT

编辑

As suggested by @patricus, this is a better way

正如@patricus 所建议的,这是一种更好的方法

$variable = "something"
return Validator::make($data, [
    'name' => 'required|in:'.$variable,
    'phone' => 'required|min:10|max:11|unique:users',
    'email' => 'required|email|max:255',
    'password' => 'required',
    'password_confirmation' => 'required',
    'user_captcha' => 'required'
]);