validate method

  1. @override
ValidationResult validate(
  1. T? value, {
  2. bool stopOnFirstError = false,
})

Implementation

@override
ValidationResult validate(T? value, {bool stopOnFirstError = false}) {
  if (value == null) {
    return ValidationResult.failure(['Value must not be null.']);
  }

  List<String>? collectedErrors;

  for (final validator in validators) {
    final (valid, error) = validator(value, context);

    // If any validator passes, return success immediately
    if (valid) {
      return ValidationResult.success();
    }

    // Collect error if validator fails
    if (error != null) {
      collectedErrors ??= [];
      collectedErrors.add(error);
    }

    // If stopOnFirstError is true, we can stop after the first failure
    // since we know no validator has passed yet
    if (stopOnFirstError && collectedErrors != null) {
      return ValidationResult.failure([collectedErrors.first]);
    }
  }

  // If no validators passed, return all collected errors
  if (collectedErrors == null || collectedErrors.isEmpty) {
    return ValidationResult.failure(['No validators passed.']);
  }

  final errors = List.generate(
    collectedErrors.length,
    (i) => collectedErrors![i],
    growable: false,
  );

  return ValidationResult.failure(errors);
}