簡體   English   中英

驗證 select 下拉菜單。 只有一個選項是正確的提交表格

[英]Validate select dropdown. Only one option is correct to submit the form

所以我有一個帶有文本框的簡單表單,帶有 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

還有我的 Controller:

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 選項制作相同類型的錯誤。

html 表單中的 Select 工作方式不同

<select name="engine">
   <option value="bing">bing</option>
</select>

在上面的代碼中,當您在請求中提交數據時將是

engine = bing

所以你必須在'engine' key上進行驗證。 在您的代碼中,您必須在searchEngine上進行驗證

// 選項一:'in' 采用逗號分隔的可接受值列表$rules = [ 'engine' => 'in:google', ];

添加此規則並檢查它是否有效根據您的要求更改鍵值

https://laravel.com/docs/5.5/validation#rule-in

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM