Reputation: 251
I would like to implement an HTML5 input pattern to validate if input text contains the - (
characters. There can be characters before and after this text.
How should I proceed?
Upvotes: 0
Views: 2745
Reputation: 2022
An HTML5 input pattern is basically a regular expression, akin to the ones used in JavaScript.
In your case, you want to have a regexp that matches the characters '-(' anywhere in the word:
<input type="text" pattern="\.*\-\(\.*">
A brief explanation
\.
matches any character, *
means it will match zero or more times\-\(
matches '-(' exactly once, the backslashes are needed because both - and ( are special characters\.*
is like the one in the beginning and will match any following characters zero or more timesYou can test this regex on regex101, the highlighted lines are the ones matching the regexp provided.
pattern
A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
You can also use the MDN page about regular expressions as reference for creating input patterns, since the syntax is the same.
Also, you can find lots of regular expressions to validate various inputs at HTML5Pattern
Upvotes: 2