validate method

  1. @override
String validate(
  1. String field,
  2. dynamic value
)
override

Implementation

@override
String validate(String field, dynamic value) {
  if (value == null) {
    if (required) {
      throw ValidationError(field, 'Field "$field" is required');
    }
    return '';
  }

  if (value is! String) {
    throw ValidationError(field, 'Expected string, got ${value.runtimeType}', value);
  }

  final str = value as String;

  if (required && str.isEmpty) {
    throw ValidationError(field, 'Field "$field" cannot be empty');
  }

  if (minLength != null && str.length < minLength!) {
    throw ValidationError(field, 'Must be at least $minLength characters long', str);
  }

  if (maxLength != null && str.length > maxLength!) {
    throw ValidationError(field, 'Must be at most $maxLength characters long', str);
  }

  if (pattern != null && !pattern!.hasMatch(str)) {
    throw ValidationError(field, 'Invalid format', str);
  }

  if (allowedValues != null && !allowedValues!.contains(str)) {
    throw ValidationError(field, 'Must be one of: ${allowedValues!.join(', ')}', str);
  }

  return str;
}