簡體   English   中英

如何驗證輸入 type="text" 元素只接受某些內容?

[英]How to validate an input type="text" element to only accept certain content?

我有一個文本輸入字段:

<input type="text" name="email" size="25" placeholder="Email Address" required/>

有沒有辦法格式化輸入字段以僅允許某些文本有效?

例如:在該特定文本字段中,用戶必須輸入以@hotmail.co.uk結尾的 email 地址。 任何其他 email 域,例如@yahoo.com將無效,因此在單擊提交時將顯示錯誤(不會注冊用戶)。

您可以使用HTML5 pattern屬性來驗證字符串是否以@hotmail.co.uk結尾。

在這種情況下,您可以使用以下正則表達式:

^.*@hotmail\.co\.uk$

 <form> <input type="text" name="email" pattern="^.*@hotmail\\.co\\.uk$" size="25" placeholder="Email Address" required/> <input type="submit" /> </form> 

另外,您也可以將input事件偵聽器附加到元素上並手動檢查。 這只是一個基本示例,您可以根據自己的需要進行自定義。 我仍然建議通過使用此問題中的正則表達式來驗證該值是一個有效的電子郵件地址。

 $('input[name="email"]').on('input', function(e) { var isValid = this.value.match(/^.*@hotmail\\.co\\.uk$/) !== null; $(this).toggleClass('isValid', isValid); }); 
 .isValid { background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" name="email" size="25" placeholder="Email Address" required/> <input type="submit" /> </form> 

使用“模式”屬性的擴展答案(來自Josh Crozier):

用戶更改輸入的值后,您可以檢查輸入是否有效:

另外,您可以在用戶鍵入值時測試輸入,並突出顯示邊框:

 function check(el) { if (new RegExp(el.pattern).test(el.value) == false) { alert("Bad Input") } } function test(el) { if (new RegExp(el.pattern).test(el.value) == false) { el.classList.add("bad") } else { el.classList.remove("bad") } } 
 .bad { border-color: red; } 
 <input pattern="^.*@hotmail\\.co\\.uk$" onchange="check(this)" oninput="test(this)" type="text" name="email" size="25" placeholder="Email Address" required/> 

有許多解決方案可用:

  • 使用javascript驗證表單。

  • 使用2個輸入:用戶名的文本輸入和“ @ site.com”的選擇選項或單選按鈕

  • 輸入的模式屬性

  • 暫無
    暫無

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

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