FileName static method

String? Function(String? value)? FileName({
  1. String errorMessage = 'Invalid File Name',
  2. String? next(
    1. String value
    )?,
  3. List<String>? extensionWhereIn,
})

Returns a validator that checks if a file name is valid.

Arguments :

  • errorMessage : The error message to return if the string does not match the pattern.
  • next : A validator to run after this validator.
  • extensionWhereIn : A list of allowed extensions. If not provided, all extensions are allowed.

Usage :

TextFormField(
validator: Validators.FileName()
),

Implementation

static String? Function(String? value)? FileName({
  String errorMessage = 'Invalid File Name',
  String? Function(String value)? next,
  List<String>? extensionWhereIn,
}) {
  assert(extensionWhereIn == null || extensionWhereIn.isNotEmpty,
      'extensionWhereIn cannot be empty');
  return (v) {
    if (v == null || v.trim().isEmpty) {
      return null;
    }

    // validate file name without extension
    if (!RegExp(r'^[a-zA-Z0-9-_]+$').hasMatch(v.split('.').first)) {
      return errorMessage;
    }

    if (extensionWhereIn != null) {
      final ext = v.split('.').last;
      if (!extensionWhereIn.contains(ext)) {
        return errorMessage;
      }
    }

    if (next != null) {
      return next(v);
    }

    return null;
  };
}