isURL static method

bool isURL(
  1. String value, {
  2. List<String?> protocols = const ['http', 'https', 'ftp'],
  3. bool requireTld = true,
  4. bool requireProtocol = false,
})

check if the string value is a URL

  • protocols sets the list of allowed protocols
  • requireTld sets if TLD is required
  • requireProtocol is a bool that sets if protocol is required for validation

Implementation

static bool isURL(
  String value, {
  List<String?> protocols = const ['http', 'https', 'ftp'],
  bool requireTld = true,
  bool requireProtocol = false,
}) {
  if (value.isEmpty || value.length > 2083 || value.startsWith('mailto:')) {
    return false;
  }

  dynamic protocol, user, auth, host, hostname, port, portStr, path, query, hash, split;

  // check protocol
  split = value.split('://');
  if (split.length > 1) {
    protocol = _shift(split);
    if (!protocols.contains(protocol)) {
      return false;
    }
  } else if (requireProtocol == true) {
    return false;
  }
  value = split.join('://');

  // check hash
  split = value.split('#');
  value = _shift(split);
  hash = split.join('#');
  if (hash != null && hash != "" && RegExp(r'\s').hasMatch(hash)) {
    return false;
  }

  // check query params
  split = value.split('?');
  value = _shift(split);
  query = split.join('?');
  if (query != null && query != "" && RegExp(r'\s').hasMatch(query)) {
    return false;
  }

  // check path
  split = value.split('/');
  value = _shift(split);
  path = split.join('/');
  if (path != null && path != "" && RegExp(r'\s').hasMatch(path)) {
    return false;
  }

  // check auth type urls
  split = value.split('@');
  if (split.length > 1) {
    auth = _shift(split);
    if (auth.indexOf(':') >= 0) {
      auth = auth.split(':');
      user = _shift(auth);
      if (!RegExp(r'^\S+$').hasMatch(user)) {
        return false;
      }
      if (!RegExp(r'^\S*$').hasMatch(user)) {
        return false;
      }
    }
  }

  // check hostname
  hostname = split.join('@');
  split = hostname.split(':');
  host = _shift(split);
  if (split.length > 0) {
    portStr = split.join(':');
    try {
      port = int.parse(portStr, radix: 10);
    } catch (e) {
      return false;
    }
    if (!RegExp(r'^[0-9]+$').hasMatch(portStr) || port <= 0 || port > 65535) {
      return false;
    }
  }

  if (!isIP(host) && !isFQDN(host, requireTld: requireTld) && host != 'localhost') {
    return false;
  }

  return true;
}