tryFix method

String? tryFix({
  1. bool allowTopLevelDomains = false,
  2. bool allowInternational = true,
})

Tries to turn address into a valid email address.

This method first trims address.

  1. If the trimmed address is already valid, it returns the trimmed address.

  2. Otherwise, it tries to fix the address by removing unsupported characters from the local part and the domain part. It does not try to fix a missing @ or more than one @. The fixed address is then checked with the same rules used by isValid, and it returns null if the address cannot be fixed into a valid email address.

Note: This method may change the meaning of the email address. Use it only when you really want to guess what the correct address is.

Implementation

String? tryFix({bool allowTopLevelDomains = false, bool allowInternational = true}) {
  final trimmed = address.trim();

  if (Email(trimmed).isValid(
    allowTopLevelDomains: allowTopLevelDomains,
    allowInternational: allowInternational,
  )) {
    return trimmed;
  }

  final atIndex = trimmed.indexOf('@');
  if (atIndex == -1) return null;
  if (trimmed.indexOf('@', atIndex + 1) != -1) return null;

  final localPart = trimmed
      .substring(0, atIndex)
      .split('')
      .where(
        (char) => _isAllowedLocalChar(char, allowInternational: allowInternational),
      )
      .join();

  final domainPart = trimmed
      .substring(atIndex + 1)
      .split('')
      .where(
        (char) => _isAllowedDomainChar(char, allowInternational: allowInternational),
      )
      .join();

  final cleanedLocalPart = localPart.replaceAll(RegExp(r'^\.+|\.+$'), '');
  final cleanedDomainPart = domainPart.replaceAll(RegExp(r'^[.-]+|[.-]+$'), '');

  final cleaned = '$cleanedLocalPart@$cleanedDomainPart';

  if (!Email(cleaned).isValid(
    allowTopLevelDomains: allowTopLevelDomains,
    allowInternational: allowInternational,
  )) {
    return null;
  }

  return cleaned;
}