Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/MiniValidation/TypeDetailsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,15 @@ private static (ValidationAttribute[]?, DisplayAttribute?, SkipRecursionAttribut
}
}

// Deduplicate validation attributes by type and error message
if (validationAttributes is not null)
{
validationAttributes = validationAttributes
.GroupBy(a => a.GetType().FullName + ":" + a.FormatErrorMessage(property.Name))
.Select(g => g.First())
.ToList();
}

return new(validationAttributes?.ToArray(), displayAttribute, skipRecursionAttribute);
}

Expand Down
19 changes: 19 additions & 0 deletions tests/MiniValidation.UnitTests/TryValidate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -464,4 +464,23 @@ public async Task TryValidateAsync_With_Attribute_Attached_Via_TypeDescriptor()
Assert.Single(errors["PropertyToBeRequired"]);
Assert.Single(errors["AnotherProperty"]);
}


private class TestResults
{
[MinLength(3)]
public string ErrorCode { get; set; } = string.Empty;
}

[Fact]
public void MinLengthAttribute_ShouldNotProduceDuplicateErrors()
{
var testObj = new TestResults { ErrorCode = "12" };
var isValid = MiniValidator.TryValidate(testObj, out var errors);

Assert.False(isValid);
Assert.True(errors.ContainsKey(nameof(TestResults.ErrorCode)));
var errorMessages = errors[nameof(TestResults.ErrorCode)];
Assert.Single(errorMessages);
}
}