Search code examples
regexdnsfqdn

Validate a 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.


Solution

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