checkString function

void checkString(
  1. dynamic input,
  2. String parameterName, {
  3. int? maxLength,
  4. int? minLength,
  5. RegExp? pattern,
})

Checks the input against the given String validators.

Throws an FormatException when the input is not:

  • matching the given pattern.
  • longer than minLength.
  • shorter than maxLength.

Implementation

void checkString(
  dynamic input,
  String parameterName, {
  int? maxLength,
  int? minLength,
  RegExp? pattern,
}) {
  String value;
  if (input is JsonObject && input.isString) {
    value = input.asString;
  } else if (input is String) {
    value = input;
  } else {
    return;
  }

  if (pattern != null && !pattern.hasMatch(value)) {
    throw FormatException('Invalid value "$input" for parameter "$parameterName" with pattern "${pattern.pattern}"');
  }

  if (minLength != null && value.length < minLength) {
    throw FormatException(
      'Parameter "$parameterName" has to be at least $minLength characters long but was ${value.length} long',
    );
  }

  if (maxLength != null && value.length > maxLength) {
    throw FormatException(
      'Parameter "$parameterName" has to be at most $maxLength characters long but was ${value.length} long',
    );
  }
}