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

时间:2013-06-12 09:50:59

标签: regex html5 validation

我搜索了很多,但我被卡住了。

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

YYYY.ordernumber

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

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

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

您可以将这两个属性与<input>

一起使用
pattern="^[0-9]{4}\.(?!0+$)([0-9]{1,6}|1000000)$"
required

E.g。

<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代替。