HTML <input> pattern 屬性
定義和用法
pattern
屬性規定正則表達式,在提交表單時根據該正則表達式檢查 <input> 元素的值。
注意:pattern
屬性適用于以下輸入類型:
- text
- date
- search
- url
- tel
- password
提示:使用 全局的 title 屬性 來描述該模式,以幫助用戶理解。
提示:請在我們的 JavaScript 教程 中學習有關正則表達式的更多知識。
實例
例子 1
下面是包含一個輸入字段的 HTML 表單,該字段只能包含三個字母(不能包含數字或特殊字符):
<form action="/action_page.php"> <label for="country_code">國家代碼:</label> <input type="text" id="country_code" name="country_code" pattern="[A-Za-z]{3}" title="三字母的國家代碼"><br><br> <input type="submit"> </form>
例子 2
下面是一個 type 屬性為 "password" 的 <input> 元素,必須包含至少 8 個字符:
<form action="/action_page.php"> <label for="pwd">密碼:</label> <input type="password" id="pwd" name="pwd" pattern=".{8,}" title="八個或更多的字符"> <input type="submit"> </form>
例子 3
下面是一個 type 屬性為 "password" 的 <input> 元素,必須包含 8 個或更多字符,至少包含一個數字,一個大寫字母和一個小寫字母:
<form action="/action_page.php"> <label for="pwd">密碼:</label> <input type="password" id="pwd" name="pwd" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="必須包含至少八個字符,其中必須包含一個數字、一個大寫字母和一個小寫字母"> <input type="submit"> </form>
例子 4
下面是一個 type 屬性為 "email" 的 <input> 元素,必須按照以下順序:characters@characters.domain。
由字符和 @ 符號組成,后面跟著更多字符,然后是一個 "." 符號。在 "." 符號后面,至少添加兩個從 a 到 z 的字母:
<form action="/action_page.php"> <label for="email">電郵:</label> <input type="email" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"> <input type="submit"> </form>
例子 5
下面是一個 type 屬性為 "search" 的 <input> 元素,不能包含以下字符: ' 或 " 。
<form action="/action_page.php"> <label for="search">Search:</label> <input type="search" id="search" name="search" pattern="[^'\x22]+" title="無效輸入"> <input type="submit"> </form>
例子 6
下面是一個 type 屬性為 "url" 的 <input> 元素,必須以 http:// 或 https:// 開頭,后面跟著至少一個字符:
<form action="/action_page.php"> <label for="website">Homepage:</label> <input type="url" id="website" name="website" pattern="https?://.+" title="包含 http://"> <input type="submit"> </form>
語法
<input pattern="regexp">
屬性值
值 | 描述 |
---|---|
regexp | 規定檢查 <input> 元素值的正則表達式。 |
瀏覽器支持
表中的數字注明了首個完全支持該屬性的瀏覽器版本。
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
5.0 | 10.0 | 4.0 | 10.1 | 9.6 |
注釋:pattern
屬性是 HTML5 中的新屬性。