我搜索了很多,但我卡住了。自定義HTML5驗證模式:YYYY.anynumber
HTML5中有一件很酷的事情,即所需的模式。這對電子郵件/電話/日期驗證非常有用。我在我的小項目中使用它來檢查數字。我需要的是一個模式:
YYYY.ordernumber
訂單號可以是任何數量從1到1000000
我試圖修改一些YYYY.MM
模式我的情況,但沒有運氣。我輸入的內容沒有通過驗證。
任何人都可以請幫忙嗎?
我搜索了很多,但我卡住了。自定義HTML5驗證模式:YYYY.anynumber
HTML5中有一件很酷的事情,即所需的模式。這對電子郵件/電話/日期驗證非常有用。我在我的小項目中使用它來檢查數字。我需要的是一個模式:
YYYY.ordernumber
訂單號可以是任何數量從1到1000000
我試圖修改一些YYYY.MM
模式我的情況,但沒有運氣。我輸入的內容沒有通過驗證。
任何人都可以請幫忙嗎?
更新:增加了向前看以確保'ordernumber'> 0(感謝M42在評論中的評論)。
您可以使用這兩個屬性與<input>
:
pattern="^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$"
required
例如
<input type="text" placeHolder="YYYY.ordernumber" title="YYYY.ordernumber"
pattern="^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$" required />
還參見本short demo。
正則表達式的簡短解釋:
^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$ _____________
^\______/\/\_____/ \________/\______/ ^___|match the end|
| | | |_(*2) |_ |_____ |of the string|
_______| | |____ | |
_________|__ _______|_____ _|______ _|________ _|______
|match the | |match exactly| |match a | |match 1 to| |or match|
|beggining of| |4 digits | |dot (*1)| |6 digits | |1000000 |
|the string |
(*1): '.' is a special character in regex, so it has to be escaped ('.').
(*2): This is a negative lookahead which does consume any characters, but looks ahead and makes sure that the rest of the string in not consisted of zeros only.
只是爲了完整性的緣故:
我必須指出的事實是[0-9]
匹配只有數字0-9。如果您需要也匹配其他數字字符,如東阿拉伯數字(٠١٢٣٤٥٦٧٨٩
),您可以使用\d
來代替。
** + 1 **爲好的解釋 – HamZa
非常感謝!我的問題解決了。 –
對於不需要的訂單號,它將匹配「0」。 – Toto