dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.37k stars 9.99k forks source link

Blazor ValidationMessage issue when using custom validation attributes #38258

Closed HTK-SSE closed 2 years ago

HTK-SSE commented 2 years ago

Problem with Blazor EditForm / UI validation:

If you´re using any custom data annotations validation attributes and submit an invalid model, the Validator correctly recognize that it´s invalid. Also the validation summary will display correctly but the input element with the binded value as well as the ValidationMessage razor element looses their error states after submit.

image

public class MinDateNow : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) => ((value as DateTime?).Value >= DateTime.Now) ? ValidationResult.Success : new ValidationResult("Das Start-Datum darf nicht in der Vergangenheit liegen."); }

[Required(ErrorMessage = "Es muss immer ein Start-Datum bestimmt werden.")] [MinDateNow] public DateTime? ValidFrom { get; set; } = DateTime.Now;

<InputDate TValue="DateTime?" @bind-Value="Model.Deviation.ValidUntil" /> <ValidationMessage For="(() => Model.Deviation.ValidUntil)" style="font-size:small;" />

mkArtakMSFT commented 2 years ago

Thanks for contacting us. You're missing to include MemberName as part of validation result. Here are the docs to help you with that: https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-6.0#custom-validation-attributes