HTML input pattern not working

2020-02-07 12:41发布

问题:

.*(\d{3}\-\d{3}\-\d{2}\-\d{2}|\d{3}\-\d{2}\-\d{2}\-\d{3}|\d{10}).* this pattern was working fine. But suddenly it stop working in chrome and opera lately. What's going on here ? What a problem is here and how it's wrong? Opera is informing about invalid escape, same in chrome. It works fine when im checking it in js.

<form>
<input type="text" pattern=".*(\d{3}\-\d{3}\-\d{2}\-\d{2}|\d{3}\-\d{2}\-\d{2}\-\d{3}|\d{10}).*">
<button>
Send
</button>
</form>

回答1:

The point is that Chrome and Firefox already support ES6 regex specifications and support the Unicode mode by default.

Unicode patterns have stricter rules as to what characters can be escaped inside the pattern. See this reference:

IdentityEscape: In BMP patterns, many characters can be prefixed with a backslash and are interpreted as themselves (for example: if \u is not followed by four hexadecimal digits, it is interpreted as u). In Unicode patterns that only works for the following characters (which frees up \u for Unicode code point escapes): ^ $ \ . * + ? ( ) [ ] { } |

The same set of chars is referred to as SyntaxCharacter in the ES6 specs page.

So, you can only escape the - inside the character class where it is considered a special character and to make it a literal you can escape it. Everywhere else it must not be escaped.

<form>
  <input type="text" pattern=".*(\d{3}-\d{3}-\d{2}-\d{2}|\d{3}-\d{2}-\d{2}-\d{3}|\d{10}).*">
  <input type=Submit>
 </form>



回答2:

Try to use below concept to implement to validate the date format

<form onsubmit="alert('Submitted.');return false;"><input required="" pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}" value="" name="dates_pattern0" id="dates_pattern0" list="dates_pattern0_datalist" placeholder="Try it out." type="text"><input value="»" type="submit"></form>

you can find more validations by this link - http://html5pattern.com/Dates