validateUrl method

String validateUrl()

Implementation

String validateUrl() {
  // Trim any leading/trailing spaces
  var url = (this ?? '').trim();

  // Use a regular expression to validate if the URL has a valid structure
  final regex = RegExp(
    r'^(http://|https://|www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?(/.*)?$',
  );

  // If the URL doesn't match the regex, return an empty string
  if (!regex.hasMatch(url)) {
    return '';
  }

  // Remove any existing protocols or 'www.' from the start of the URL
  url = url.replaceFirst(RegExp(r'^(http://|https://|www\.)'), '');

  // Add the custom "https://www." prefix
  url = 'https://www.$url';

  // Return the modified URL
  return url;
}