【发布时间】:2020-06-30 18:53:54
【问题描述】:
所以我有一个带有文本框的简单表单,带有 2 个选项和一个提交按钮的下拉菜单。我有一个包含两个值的下拉列表 - Google 和 Bing。如果您选择 Bing,我希望它引发错误。我为只接受字母的文本框做了类似的事情。如果您在输入框中添加数字,则会显示正则表达式错误。如何为我的下拉菜单获取此信息?
我的刀片文件:
<form action="{{route('redirectURL')}}" method="GET">
<input {!!$errors->has('searchText') ? 'style="background-color: #faa"' : '' !!} type="text"
value="
{{old('searchText')}}" name="searchText" pattern="[a-zA-Z0-9]{5,30}" title="Vain [a-zA-Z0-9]{5,30}
hyväksytään"> <input type="submit" name="submit"><br>
@error('searchText')
<div style="background-color: lightgrey; width:230px;">
{{$message}}
</div>
@enderror
<select name="searchEngine">
<option name="Google" value="http://www.google.com/search?q=" @if(old('searchEngine') ==
"http://www.google.com/search?q=") {{'selected'}} @endif >Google</option>
<option name="Bing" value="http://www.bing.com/search?q=" @if(old('searchEngine') ==
"http://www.bing.com/search?q=") {{'selected'}} @endif>Bing</option>
</select>
@error('Google')
<div style="background-color: lightgrey; width:230px">
{{$message}}
</div>
@enderror
还有我的控制器:
public function searchURL(){
$validator = request()->validate([
'searchText'=> ['required','regex:/^[a-zA-Z]{5,30}$/'],
'Google' => 'required'
],
['searchText.regex' => 'I accept only letters!',
'Google.required' => 'Dont use Bing... use Google!'
]
);
文本框正则表达式错误显示正常,但我不知道如何为 Bing 选项生成相同类型的错误。
【问题讨论】:
-
Opps,我发现一个错误
option name="Google"选项不能包含name属性。它只可以取值w3schools.com/tags/tag_select.aspselect元素是option的父元素,它可以取name属性 -
我尝试将您的代码更改为
if ($request->searchEngine == "http://www.bing.com/search?q=") { return Redirect::back()->withErrors(['engine', 'Dont use Bing... use Google!']); }但它也不起作用。也许我需要使用其他技术?
标签: php laravel validation