Reputation: 2407
So I have the following Regex URL validator:
[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+
It works perfectly well for my needs, except that it accepts urls without a domain for example www.test
works.
How can I modify it to validate for a domain? (Any domain should be accepted not just .com
Upvotes: 0
Views: 42
Reputation: 3114
You could do it like this to account for unicode:
^\p{L}+\.\p{L}+(\.\p{L}{2,})+
\p{L}
or\p{Letter}
: any kind of letter from any language.
So with this we match for a group of one or more letters (sudomain) followed by a . followed by a group of one or more letters (main domain) followed by any number of groups of . with two or more letters (domain suffix).
Upvotes: 0
Reputation: 521997
Just make the last group in your regex mandatory as appearing two or more times:
[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,}){2,}
As a disclaimer, and as @Wiktor will probably comment, you might want to use a regex pattern for validating URLs which already has been tested thoroughly. While this answer may fix your immediate problem, there are most likely other edge cases which exist.
Upvotes: 2