validate method

  1. @override
String? validate(
  1. String? value
)
override

Validates the value and returns an error string if it fails, or null if it passes.

Implementation

@override
String? validate(String? value) {
  if (value == null || value.isEmpty) return null;

  final isV4 = RegExp(r'^(\d{1,3}\.){3}\d{1,3}$').hasMatch(value);
  // Note: A full IPv6 regex is very complex, this catches basic fully expanded ones.
  // For a robust implementation without dependencies, `Uri.parseIPv6Address` could be used
  // but it throws. We'll use a better regex or `InternetAddress` if available, but
  // `dart:io` isn't recommended for pure Dart packages if web support is needed.
  // We will stick to a moderately robust regex for v6:
  final robustV6 = RegExp(
          r'^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$')
      .hasMatch(value);

  if (v4Only && !isV4) return message;
  if (v6Only && !robustV6) return message;
  if (!v4Only && !v6Only && !isV4 && !robustV6) return message;

  // Extra v4 block check to ensure segments <= 255
  if (isV4) {
    final parts = value.split('.');
    for (final part in parts) {
      if ((int.tryParse(part) ?? 256) > 255) return message;
    }
  }

  return null;
}