HTML字段校验,pattern属性

问题描述:

我不知道是什么大胆的部分是指:HTML字段校验,pattern属性

<input name="zip_code" type="text" pattern="\d{5}(-\d{4})?" required="required" />

谁能帮助我?

+0

5位数则'-'后跟4个其它数字,其被分组例如。 '12345-6789' – Thielicious

+0

https://regex101.com/r/YLwcDv/2/ – Thielicious

\d{5}意味着5位是必需的, (-\d{4})?意味着字符 “ - ” 和其他4位是可选

pattern="\d{5}(-\d{4})?" 

手段

  1. 开始以5个数字
  2. 其次一个破折号(可选)
  3. 后跟4位数字(可选)

48412 - Accepted 
4488 - Rejected 
44775-4412 - Accepted 
74547-45745 - Rejected 

规则如下

^  a string that starts with... 
(  either 
    \d a digit (0-9)... 
    {4} that repeats four times... 
|  or 
    \d a digit (0-9)... 
    {6} that repeats six times... 
) 
$ and then ends