选择框验证(在 Laravel 中)

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

Select box validation (in laravel)

phpvalidationselectlaravel

提问by Kanav

I have a form containing text inputs and select box. I was trying to apply laravel validation. Now i wanted to retain the user inputted values, if validation doesn't success.

我有一个包含文本输入和选择框的表单。我试图应用 Laravel 验证。现在我想保留用户输入的值,如果验证不成功。

I am able to get this done on input box, but not on select box. How to show previously selected value(in select box) if validation doesn't pass.

我可以在输入框上完成这项工作,但不能在选择框上完成。如果验证未通过,如何显示先前选择的值(在选择框中)。

This is my code

这是我的代码

{{Form::select('vehicles_year', $modelYears, '-1', ['id' => 'vehicles_year'])}}

<span class="help-block" id="vehicles_year_error">
    @if ($errors->has('vehicles_year')) {{$errors->first('vehicles_year')}} @endif
</span>

-1 is the key of default value that i am showing when the form loads.

-1 是我在表单加载时显示的默认值的键。

回答by Andreyco

What I do is that I add "default" option which value is set to "nothing".
In validation rules I say this value is required. If user does not pick one of the other options, validation fails.

我所做的是添加“默认”选项,该选项的值设置为“无”。
在验证规则中,我说这个值是必需的。如果用户未选择其他选项之一,则验证失败。

$options = [
    'value' => 'label',
    'value' => 'label',
    'value' => 'label',
    'value' => 'label',
];

$options = array_merge(['' => 'please select'], $options);

{{ Form::select('vehicles_year', $options, Input::old('vehicles_year'), ['id' => 'vehicles_year']) }}

@if ($errors->has('vehicles_year'))
    <span class="help-block" id="vehicles_year_error">
         {{ $errors->first('vehicles_year') }}
    </span>
@endif

// Validation rules somewhere...
$rules = [
    ...
    'vehicles_year' => 'required|...',
    ...
];

回答by JulienTant

The controller code is missing. I will suppose your handle the POSTin a controller method and then you Redirect::back()->withInput();

控制器代码丢失。我会假设你POST在控制器方法中处理,然后你Redirect::back()->withInput();

Thanks to ->withInput()You can use in your view something like Input::old()to get the Input values of your previous request.

感谢->withInput()您可以在您的视图中使用类似的东西Input::old()来获取您之前请求的输入值。

So to select your previous item ANDhave -1 by default, you can use Input::old('vehicles_year', -1)

因此AND,默认情况下要选择上一个项目具有 -1,您可以使用Input::old('vehicles_year', -1)

The first argument is the Input name, and the second is the default value.

第一个参数是输入名称,第二个参数是默认值。

{{Form::select('vehicles_year', $modelYears, Input::old('vehicles_year', -1), ['id' => 'vehicles_year'])}}

Hope this helps

希望这可以帮助