Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to match fully qualified domain name, without protocol, optional subdomain

I haven't been able to find this one and what I'm trying isn't quite working out for me.

I want to match only domains that:

  • don't contain a protocol (http, https, ftp)
  • optionally include a subdomain
  • don't start with a hyphen but can contain a hyphen

Example domains that would match:

  • domain.com
  • example.domain.com
  • example.domain-hyphen.com
  • www.domain.com
  • example.museum

Example domains that would not match:

  • http://example.com
  • subdomain.-example.com
  • example.com/parameter
  • example.com?anything
  • www.subdomain.domain.com

What I've currently got:

/^(?!:\/\/)(^[a-zA-Z0-9])?.[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}?$/i

It's not matching protocols, allowing hyphen inside the domain, not allowing trailing characters after the TLD, and is allowing a subdomain (but only 1 character).

I still need to allow subdomains of any length, not allow www.subdomain.domain.com and not allow a leading hyphen.

like image 620
Jared Eitnier Avatar asked May 09 '13 14:05

Jared Eitnier


People also ask

How do I find the regex for a domain name?

The domain name should be a-z or A-Z or 0-9 and hyphen (-). The domain name should be between 1 and 63 characters long. The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-). The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters.

How do I know if my FQDN is valid?

Any string containing at least one dot is potentially a valid fqdn. The usage of the "host" command makes sure the string resolves to an ip address, which means it is actually a fqdn.

Can a subdomain be a FQDN?

A FQDN is a domain name that includes a host name, a root domain and a top level domain. It may also include additional subdomains between the root domain and the host name. Almost all individual parts of a FQDN are technically subdomains. The only part of a domain that isn't a subdomain is the root domain.


1 Answers

Try

/^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,6}?$/i
like image 60
dda Avatar answered Oct 11 '22 12:10

dda