isUrl method

bool isUrl([
  1. Map<String, Object>? options
])

Check if the string is a URL

options is a Map which defaults to { 'protocols': ['http','https','ftp'], 'require_tld': true, 'require_protocol': false, 'allow_underscores': false }.

Implementation

bool isUrl([Map<String, Object>? options]) {
  var str = this;
  if (str.isEmpty || str.length > 2083 || str.indexOf('mailto:') == 0) {
    return false;
  }

  final defaultUrlOptions = {
    'protocols': ['http', 'https', 'ftp'],
    'require_tld': true,
    'require_protocol': false,
    'allow_underscores': false,
  };

  options = options?.merge(defaultUrlOptions) ?? defaultUrlOptions;

  // check protocol
  var split = str.split('://');
  if (split.length > 1) {
    final protocol = split.shift();
    final protocols = options['protocols'] as List<String>;
    if (!protocols.contains(protocol)) {
      return false;
    }
  } else if (options['require_protocol'] == true) {
    return false;
  }
  str = split.join('://');

  // check hash
  split = str.split('#');
  str = split.shift() ?? "";
  final hash = split.join('#');
  if (hash.isNotEmpty && RegExp(r'\s').hasMatch(hash)) {
    return false;
  }

  // check query params
  split = str.isNotEmpty ? str.split('?') : [];
  str = split.shift() ?? "";
  final query = split.join('?');
  if (query != "" && RegExp(r'\s').hasMatch(query)) {
    return false;
  }

  // check path
  split = str.isNotEmpty ? str.split('/') : [];
  str = split.shift() ?? "";
  final path = split.join('/');
  if (path != "" && RegExp(r'\s').hasMatch(path)) {
    return false;
  }

  // check auth type urls
  split = str.isNotEmpty ? str.split('@') : [];
  if (split.length > 1) {
    final auth = split.shift();
    if (auth != null && auth.contains(':')) {
      // final auth = auth.split(':');
      final parts = auth.split(':');
      final user = parts.shift();
      if (user == null || !RegExp(r'^\S+$').hasMatch(user)) {
        return false;
      }
      final pass = parts.join(':');
      if (!RegExp(r'^\S*$').hasMatch(pass)) {
        return false;
      }
    }
  }

  // check hostname
  final hostname = split.join('@');
  split = hostname.split(':');
  final host = split.shift();
  if (split.isNotEmpty) {
    final portStr = split.join(':');
    final port = int.tryParse(portStr, radix: 10);
    if (!RegExp(r'^[0-9]+$').hasMatch(portStr) || port == null || port <= 0 || port > 65535) {
      return false;
    }
  }

  if (host == null || !host.isIP() && !host.isFQDN(options) && host != 'localhost') {
    return false;
  }

  return true;
}