I\'m trying to validate the content of a using JavaScript, So I created a
validate()
function, which returns
The answers saying to not use regex are perfectly fine, but I like regex so:
^\s*(?:(?:\w+(?:-+\w+)*\.)+[a-z]+)\s*(?:,\s*(?:(?:\w+(?:-+\w+)*\.)+[a-z]+)\s*)*$
Yeah..it's not so pretty. But it works - tested on your sample cases at http://regex101.com
Edit: OK let's break it down. And only allow sub-domain-01.com
and a--b.com
and not -.com
Each subdomain thingo: \w+(?:-+\w+)*
matches string of word characters plus optionally some words with dashes preceeding it.
Each hostname: \s*(?:(?:\w+(?:-\w+)*\.)+[a-z]+)\s*
a bunch of subdomain thingos followed by a dot. Then finally followed by a string of letters only (the tld). And of course the optional spaces around the sides.
Whole thing: \s*(?:(?:\w+(?:-\w+)*\.)+[a-z]+)\s*(?:,\s*(?:(?:\w+(?:-\w+)*\.)+[a-z]+)\s*)*
a single hostname, followed by 0 or more ,hostname
s for our comma separated list.
Pretty simple really.