Çağdaş Umay
Çağdaş Umay

Reputation: 251

How to implement html5 pattern to validate input that contains specific letters?

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

Answers (1)

Vale
Vale

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 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

Upvotes: 2

Related Questions