rufl/string/
is_dns.rs

1use lazy_static::lazy_static;
2use regex::Regex;
3
4/// Checks if the string is a valid domain name.
5///
6/// # Arguments
7///
8/// * `s` - The string to check.
9///
10/// # Returns
11///
12/// Returns true if string is a valid domain name, false if not.
13///
14/// # Examples
15///
16/// ```
17/// use rufl::string;
18///
19/// assert_eq!(true, string::is_dns("abc.com"));
20///
21/// assert_eq!(true, string::is_dns("123.cn"));
22///
23/// assert_eq!(false, string::is_dns("abc@123.com"));
24///
25/// ```
26
27pub fn is_dns(s: impl AsRef<str>) -> bool {
28    DNS_REGEX.is_match(s.as_ref())
29}
30
31lazy_static! {
32    static ref DNS_REGEX: Regex =
33        Regex::new(r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$").unwrap();
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test_is_dns() {
42        assert_eq!(true, is_dns("abc.com"));
43        assert_eq!(true, is_dns("123.cn"));
44        assert_eq!(true, is_dns("123.abc.com"));
45
46        assert_eq!(false, is_dns(""));
47        assert_eq!(false, is_dns("abc@com"));
48        assert_eq!(false, is_dns("@#$.com."));
49        assert_eq!(false, is_dns("http://abc.com"));
50    }
51}