MaxLength static method

String? Function(String? value)? MaxLength({
  1. required int length,
  2. String errorMessage = 'Maximum length is *max_len*',
  3. String? next(
    1. String value
    )?,
})

Returns a validator that checks if a string is at most a certain length.

Arguments :

  • length : The maximum length of the string.
  • errorMessage : The error message to return if the string is not at most a certain length.
  • next : A validator to run after this validator.

Usage :

TextFormField(
validator: Validators.MaxLength(length: 5),
),

Implementation

static String? Function(String? value)? MaxLength({
  required int length,
  String errorMessage = 'Maximum length is *max_len*',
  String? Function(String value)? next,
}) {
  if (errorMessage.contains('*max_len*')) {
    errorMessage = errorMessage.replaceAll('*max_len*', length.toString());
  }
  return (value) {
    if (value == null || value.trim().isEmpty) {
      return null;
    }

    if (value.length > length) {
      return errorMessage;
    }

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

    return null;
  };
}