1
votes

I need to validate a known domain, like domain.com with JavaScript, but I need to validate it with any subdomain or sub-subdomains and so, and with any protocol and with any folder, sub-folder, and so, I have this regular expression:

RegEx: /http:\/\/([\.|a-z]+).domain([\.|a-z]+)\//

The problem is it not gets https/ftp/ftps... and it get domain.com/domain.org... I need to validate, something like this:

To validate: *://*.domain.com/*
Example: http://example.domain.com/subfolder2/folder24/
Example: https://subdomain.domain.com/folder/
Example: ftp://www.example.domain.com/folder2/folder/
Example: http://www.domain.com/folder/sub-folder/

I mean, any protocol, any subdomain, and any folder, and of course, all of them together too:

Example: https://example.domain.com/folder/folder/

Any idea?

1
Ask google for "regex to validate domain names" and you will find plenty.Mörre
Do you understand the expression you are using?Felix Kling
@Mörre I did, and I get regular expressions for any domain, but I need for a particular domain...Minion
@FelixKling I understand, it gets something like http://*.domain.*/* but I don't know how can I get what I need ://.domain.com/*Minion
For starters, replace domain([\.|a-z]+) with domain\.com. http of course does not match https or ftp or the like. But you can use alternation to allow more protocols.Felix Kling

1 Answers

3
votes

Try this regex:

/^(https?|ftp):\/\/[.a-z]+\.domain\.com[.a-z0-9/-]+/

This will match the domains you lisited:

http://example.domain.com/subfolder2/folder24/
https://subdomain.domain.com/folder/
ftp://www.example.domain.com/folder2/folder/
http://www.domain.com/folder/sub-folder/

How it works:

# /            - Regex start,
# ^            - Match the start of the string,
# (https?|ftp) - followed by `https`, `http` or `ftp`,
# :\/\/        - followed by `://`,
# [.a-z]+      - followed by any amount of letters or periods,
# \.           - followed by a period,
# domain\.com  - followed by the domain name,
# [.a-z0-9/-]+ - followed by the rest of a possible url.
# /            - regex end.