Z D
Z D

Reputation: 45

HTML Regex for domain name entry?

Currently I have a form accepting domain names, so I need to preclude every special character & space except for . and - being entered.

my current code:

<input type="text" name="domain-name" placeholder="i.e. example.com" pattern="^(\d|\w)+$" class="form-field w-input" required id="domain-name">

Won't accept . or -

How can I change it so that it accepts . and -

Upvotes: 1

Views: 338

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626936

The pattern attribute should look like

pattern="[\w.-]+"

Details

  • The ^ (start of string) and $ (end of string) anchors are redundant in a pattern regex since the resulting RegExp object is compiled with the ^(?: before and )$ after the string pattern typed in the attribute value
  • \w matches digits by itself, so [\w\d] = \w
  • To match . or -, you need to put \w inside a character class, [], and add . and - to this character class.

Upvotes: 1

Related Questions