allowedMimeTypes function

String? Function(List<BloomFile>) allowedMimeTypes(
  1. List<String> mimeTypes, [
  2. String? message
])

Creates a validator for BloomFileField that fails when a file's MIME type does not match mimeTypes.

Supports exact MIME types (e.g. 'image/png') and wildcards (e.g. 'image/*'). Returns message (or 'MIME type "$fileType" is not allowed. Allowed: ...' by default).

final imageField = BloomFileField(
  validators: [allowedMimeTypes(['image/png', 'image/jpeg', 'image/webp'])],
);

Implementation

String? Function(List<BloomFile>) allowedMimeTypes(List<String> mimeTypes,
    [String? message]) {
  final lowerTypes = mimeTypes.map((m) => m.toLowerCase()).toList();
  return (files) {
    for (final file in files) {
      final fileType = file.mimeType.toLowerCase();
      final matched = lowerTypes.any((allowed) {
        if (allowed.endsWith('/*')) {
          final prefix = allowed.substring(0, allowed.length - 1);
          return fileType.startsWith(prefix);
        }
        return fileType == allowed;
      });
      if (!matched) {
        return message ??
            'MIME type "$fileType" is not allowed. Allowed: ${mimeTypes.join(', ')}.';
      }
    }
    return null;
  };
}