string method

ValidatorBuilder string(
  1. String field,
  2. String? value, {
  3. bool required = false,
  4. int? minLength,
  5. int? maxLength,
  6. String? pattern,
})

String field validation

Implementation

ValidatorBuilder string(
  String field,
  String? value, {
  bool required = false,
  int? minLength,
  int? maxLength,
  String? pattern,
}) {
  final fullField = _prefix != null ? '$_prefix.$field' : field;

  _schema['properties'][field] = {
    'type': 'string',
    if (required) 'required': true,
    if (minLength != null) 'minLength': minLength,
    if (maxLength != null) 'maxLength': maxLength,
    if (pattern != null) 'pattern': pattern,
  };

  if (required && (value == null || value.trim().isEmpty)) {
    _errors.add(ValidationError('$fullField is required'));
  } else if (value != null) {
    if (minLength != null && value.length < minLength) {
      _errors.add(
        ValidationError('$fullField must be at least $minLength characters'),
      );
    }
    if (maxLength != null && value.length > maxLength) {
      _errors.add(
        ValidationError('$fullField must be at most $maxLength characters'),
      );
    }
    if (pattern != null && !RegExp(pattern).hasMatch(value)) {
      _errors.add(ValidationError('$fullField format is invalid'));
    }
  }

  return this;
}