自定义HTML5验证模式:YYYY.anynumber

Dmi*_*tel 1 regex validation html5

我google了很多,但我被卡住了.

HTML5中有一个很酷的东西,即所需的模式.它非常适合电子邮件/电话/日期验证.我在我的小项目中用它来检查数字.我需要的是一个模式:

YYYY.ordernumber
Run Code Online (Sandbox Code Playgroud)

订单号可以是1到1000000之间的任何数字.

我尝试YYYY.MM为我的案例修改一些模式,但没有运气.我输入的内容未通过验证.

有人可以帮忙吗?

gka*_*pak 5

更新:添加了一个预测,以确保'ordernumber'> 0(感谢M42在评论中的评论).

您可以将这两个属性用于<input>:

pattern="^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$"
required
Run Code Online (Sandbox Code Playgroud)

例如

<input type="text" placeHolder="YYYY.ordernumber" title="YYYY.ordernumber"
       pattern="^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$" required />
Run Code Online (Sandbox Code Playgroud)

另见这个简短的演示.


正则表达式的简短说明:

                  ^[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  |
Run Code Online (Sandbox Code Playgroud)

(*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