regexvalidationdomain-name

What is a regular expression which will match a valid domain name without a subdomain?


I need to validate a domain name:

google.com

stackoverflow.com

So a domain in its rawest form - not even a subdomain like www.

  1. Characters should only be a-z | A-Z | 0-9 and period(.) and dash(-)
  2. The domain name part should not start or end with dash (-) (e.g. -google-.com)
  3. The domain name part should be between 1 and 63 characters long
  4. The extension (TLD) can be anything under #1 rules for now, I may validate them against a list later, it should be 1 or more characters though

Edit: TLD is apparently 2-6 chars as it stands

no. 4 revised: TLD should actually be labelled "subdomain" as it should include things like .co.uk -- I would imagine the only validation possible (apart from checking against a list) would be 'after the first dot there should be one or more characters under rules #1

Thanks very much, believe me I did try!


Solution

  • Well, it's pretty straightforward a little sneakier than it looks (see comments), given your specific requirements:

    /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/
    

    But note this will reject a lot of valid domains.