Validation Result
ValidationResult is the object returned by Validate() and ValidateAsync(). Its real source of truth is Failures — a severity-aware list of everything the validation run produced. Errors/ErrorCodes/IsValid and the rest of the classic surface are computed views over Failures, filtered to Severity.Error only, kept exactly as they behaved before severity existed.
Structure
public sealed class ValidationResult
{
// The source of truth: every failure produced by this run, at every severity
public List<ValidationFailure> Failures { get; }
// true if there are no Severity.Error failures (Warning/Info never affect this)
public bool IsValid { get; }
// Back-compat view over Failures, filtered to Severity.Error: { "Email": ["Invalid", "Already exists"] }
public IReadOnlyDictionary<string, List<string>> Errors { get; }
// Back-compat view over Failures, filtered to Severity.Error with a non-null error code
public IReadOnlyDictionary<string, List<string>> ErrorCodes { get; }
// Total number of Severity.Error failures (sum across all properties)
public int ErrorCount { get; }
// Names of properties that have a Severity.Error failure
public IReadOnlyList<string> PropertyNames { get; }
}
public sealed class ValidationFailure
{
public string PropertyName { get; }
public string Message { get; }
public Severity Severity { get; } // Error (default), Warning, or Info
public string? ErrorCode { get; }
}
Note:
ErrorsandErrorCodesareIReadOnlyDictionary<string, List<string>>, computed fresh on every access fromFailures— mutating the returned dictionary has no effect on theValidationResult. UseAddFailure/AddErrorto add failures instead (see below).
IsValid and ErrorCount
var result = await validator.ValidateAsync(request);
if (!result.IsValid)
{
Console.WriteLine($"Validation failed with {result.ErrorCount} error(s).");
}
// IsValid is equivalent to: result.Errors.Count == 0
// ErrorCount is the total sum: if Email has 2 errors and Name has 1, ErrorCount is 3
Accessing Errors
By Property Directly
if (result.Errors.TryGetValue("Email", out var emailErrors))
{
foreach (var error in emailErrors)
Console.WriteLine($"Email: {error}");
}
Iterating All Errors
foreach (var (propertyName, errors) in result.Errors)
{
foreach (var error in errors)
Console.WriteLine($"{propertyName}: {error}");
}
Checking if a Property Has Errors
bool hasEmailError = result.HasErrorFor("Email");
bool hasNameError = result.HasErrorFor("Name");
Getting Errors for a Property
// Returns an empty List<string> if there are no errors for that property
List<string> emailErrors = result.ErrorsFor("Email");
Getting the First Error for a Property
// Returns null if there are no errors for that property
string? firstError = result.FirstError("Email");
PropertyNames
IReadOnlyList<string> failedProperties = result.PropertyNames;
Console.WriteLine($"Properties with errors: {string.Join(", ", failedProperties)}");
// Output: "Properties with errors: Email, Password, BirthDate"
Failures and Severity
Failures is the full list backing everything else on ValidationResult. Iterate it directly when you need to see Warning/Info failures, which never appear in Errors/ErrorCodes:
var result = await validator.ValidateAsync(request);
foreach (var failure in result.Failures)
{
Console.WriteLine($"[{failure.Severity}] {failure.PropertyName}: {failure.Message}");
}
var warnings = result.Failures.Where(f => f.Severity == Severity.Warning).ToList();
See Severity for the full picture: marking a rule non-blocking with .WithSeverity(Severity.Warning), JSON serialization of Failures, and the cases where WithSeverity doesn't apply (cross-property rules, MustAsync/DependentRuleAsync).
AddError
AddError allows manually adding errors to a ValidationResult. Useful for combining validation with business logic:
// Without error code
result.AddError("Email", "The email is already in use.");
// With error code
result.AddError("Email", "The email is already in use.", "EMAIL_ALREADY_EXISTS");
AddError is shorthand for AddFailure(property, message, Severity.Error, errorCode). Use AddFailure directly when you want to add a non-blocking failure from application code:
result.AddFailure("Discount", "Discount exceeds the recommended threshold.", Severity.Warning);
Example in a service that combines validation and business logic:
public async Task<ValidationResult> ValidateAndCheckBusinessRulesAsync(
CreateOrderRequest request,
CancellationToken ct)
{
var result = await _validator.ValidateAsync(request, ct);
if (!result.IsValid)
return result;
var customer = await _customers.GetByIdAsync(request.CustomerId, ct);
if (customer.IsBlocked)
{
result.AddError("CustomerId",
"The customer is blocked and cannot place orders.",
"CUSTOMER_BLOCKED");
}
return result;
}
ToFlatList
ToFlatList() returns all errors as a flat list of strings in the format "PropertyName: message".
var result = await validator.ValidateAsync(request);
List<string> flatErrors = result.ToFlatList();
foreach (var error in flatErrors)
Console.WriteLine(error);
// Output:
// Name: The name is required.
// Email: The email does not have a valid format.
// Email: The email is already registered.
// Password: Must have at least 8 characters.
Useful for logging:
if (!result.IsValid)
{
_logger.LogWarning("Validation failed: {Errors}",
string.Join(" | ", result.ToFlatList()));
}
Merge
Merge combines the errors from another ValidationResult into the current one:
var mainResult = await _mainValidator.ValidateAsync(request);
var addressResult = await _addressValidator.ValidateAsync(request.Address);
var paymentResult = await _paymentValidator.ValidateAsync(request.Payment);
mainResult.Merge(addressResult);
mainResult.Merge(paymentResult);
if (!mainResult.IsValid)
return BadRequest(mainResult.Errors);
ErrorCodes
ErrorCodes is a dictionary parallel to Errors that contains error codes assigned with WithErrorCode.
// Check if a specific code exists
bool hasCreditLimitError = result.ErrorCodes
.Any(kvp => kvp.Value.Contains("CREDIT_LIMIT_EXCEEDED"));
Usage in a Structured API Response
if (!result.IsValid)
{
return BadRequest(new
{
errors = result.Errors.ToDictionary(k => k.Key, v => v.Value.ToArray()),
errorCodes = result.ErrorCodes.ToDictionary(k => k.Key, v => v.Value.ToArray())
});
}
Response:
{
"errors": {
"Email": ["The email is already registered."],
"Amount": ["The amount exceeds the credit limit."]
},
"errorCodes": {
"Email": ["EMAIL_ALREADY_EXISTS"],
"Amount": ["CREDIT_LIMIT_EXCEEDED"]
}
}
Usage in ASP.NET Core with ValidationProblem
For Minimal API, Results.ValidationProblem expects Dictionary<string, string[]>:
app.MapPost("/users", async (CreateUserRequest request, IValidator<CreateUserRequest> validator) =>
{
var result = await validator.ValidateAsync(request);
if (!result.IsValid)
{
var errors = result.Errors.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.ToArray());
return Results.ValidationProblem(errors);
}
return Results.Ok();
});
Building ValidationResult Manually
Useful in tests or in validation orchestrators:
var result = new ValidationResult();
result.AddError("Name", "The name is required.", "NAME_REQUIRED");
result.AddError("Email", "The email is not valid.", "EMAIL_INVALID");
Console.WriteLine(result.IsValid); // false
Console.WriteLine(result.ErrorCount); // 2
Testing with ValidationResult
[Fact]
public async Task Name_TooShort_ShouldFailWithCorrectMessage()
{
var request = new CreateProductRequest { Name = "AB", Price = 10m };
var result = await _validator.ValidateAsync(request);
Assert.False(result.IsValid);
Assert.True(result.HasErrorFor("Name"));
Assert.Contains("at least 3 characters", result.FirstError("Name"));
}
[Fact]
public async Task ValidRequest_ShouldPass()
{
var request = new CreateProductRequest
{
Name = "Laptop Pro",
Price = 999.99m,
Stock = 10,
Category = "Electronics"
};
var result = await _validator.ValidateAsync(request);
Assert.True(result.IsValid);
Assert.Equal(0, result.ErrorCount);
}
Next Steps
- Severity —
Failures,Severity.Warning/Info, and migrating from the v2.xErrors-only model - Exceptions — ValidationException and ValidateAndThrow
- ASP.NET Core — Integration with middleware and filters