0

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?

1 Answer 1

2

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 times

You can test this regex on regex101, the highlighted lines are the ones matching the regexp provided.

From the MDN doc page

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

Sign up to request clarification or add additional context in comments.

2 Comments

I get the concept of regex now. I implemented what i want by a different approach however it was useful thank you.
The . character should not be preceded by a backslash if you want it to match any character. If preceded by a backslash it will only represent the period (.) character itself and no other characters. Also, . matches any character except line-breaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.