Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a FQDN

Tags:

regex

dns

fqdn

I found this regex at http://gskinner.com/RegExr/ to validate a FQDN domain:

(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.?)+(?:[a-zA-Z]{2,})$)

it basically works but I want to modify it to not allow hostnames of three or more chars and no domain. For example, currently this is valid:

www

This isn't:

ww

This is too:

www.test.com

I want to modify it to not allow the first example. In other words, check that there's always a domain present.

Thanks.

like image 529
Juancho Avatar asked Jan 27 '26 17:01

Juancho


1 Answers

Try this:

(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.)+(?:[a-zA-Z]{2,})$)

The question mark after the period which ends the "subdomain" section of the regex has been removed, making it mandatory rather than optional.

like image 102
Zero Piraeus Avatar answered Jan 29 '26 10:01

Zero Piraeus