Skip to content

Instantly share code, notes, and snippets.

@mortenmoulder
Created September 12, 2018 07:41
Show Gist options
  • Save mortenmoulder/11cbfdc5289b7e1c8b21643c77f63fda to your computer and use it in GitHub Desktop.
Save mortenmoulder/11cbfdc5289b7e1c8b21643c77f63fda to your computer and use it in GitHub Desktop.
Checks if a given domain is valid according to these tests
// This will make the following conditions true:
// 1) Does not match hostnames
// 2) Cannot start or end with a dot
// 3) Cannot start or end with a hyphen
// 4) Number 3 applies for the hostname as well
// 5) Two punctuations after each other is not allowed
// 6) Cannot be an IP address
// 7) Can only use the characters: [0-9A-Za-z], punctuations, and hyphens
/*
* CHECK THIS OUT: https://dotnetfiddle.net/zjg3Ep
*/
private bool IsDomainValid(string DomainName)
{
//no hostnames
if (DomainName.Split('.').Length <= 1) return false;
//cannot start or end with a dot - simply invalid
if (DomainName[0] == '.' || DomainName[DomainName.Length - 1] == '.') return false;
//cannot start or end with a hyphen - simply invalid
if (DomainName[0] == '-' || DomainName[DomainName.Length - 1] == '-') return false;
//hostname cannot start or end with a hyphen - simply invalid
if (DomainName.Split('.')[0] == "-" || DomainName.Split('.')[0][DomainName.Split('.')[0].Length - 1] == '-') return false;
//cannot have two dots right after eachother
if (DomainName.Matches($"[\\.]{2}")) return false;
//cannot be an IP
if (Uri.CheckHostName(DomainName) == UriHostNameType.IPv4) return false;
//cannot contain illegal characters
if (!DomainName.Matches($"^[a-zA-Z_0-9.-]+$")) return false;
return true;
}
@mortenmoulder
Copy link
Author

Got any updates to improve this, let me know. Also make sure to check this out: https://dotnetfiddle.net/zjg3Ep

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment