-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathisValidDomain.ts
More file actions
49 lines (39 loc) · 1.09 KB
/
isValidDomain.ts
File metadata and controls
49 lines (39 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { isEmpty, isString } from "../../lang";
/**
* Checks if a given string represents a syntactically valid domain name.
*
* @param {string} domain - The string to check for valid domain name syntax.
* @returns {boolean} `true` if the string is a syntactically valid domain name; otherwise, `false`.
* @environment `Google Apps Script`, `Browser`
*/
export function isValidDomain(domain: string): domain is string {
if (!isString(domain) || isEmpty(domain)) {
return false;
}
if (domain.includes("..")) {
return false;
}
if (
domain.startsWith("-") ||
domain.endsWith("-") ||
domain.startsWith(".") ||
domain.endsWith(".")
) {
return false;
}
const parts = domain.split(".");
if (parts.length < 2) {
return false;
}
const LABEL_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
for (const part of parts) {
if (part.length === 0) {
return false;
}
if (!LABEL_PATTERN.test(part)) {
return false;
}
}
const tld = parts[parts.length - 1];
return !(tld.length < 2 || !/^[a-zA-Z]+$/.test(tld));
}