Closed katiep23 closed 4 years ago
Here is my custom validation if that matters at all:
class CurrentOrFutureDateValidation: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value==null)
{
return ValidationResult.Success;
}
DateTime dt = (DateTime)value;
if (dt >= DateTime.Today)
{
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage ?? "Date selected must be greater or equal to today's date.");
}
}
@katiep23 thanks for contacting us.
Can you provide a minimal repro project that illustrates the issue?
Thanks for the repro project @katiep23. Blazor does two kinds of validation:
DataAnnotationsValidator
component associates all validation results that are reported with the field. This explains why you see the error message associate with the field when you enter it.DataAnnotationsValidator
component attempts to figure out the field based on the member name that the validation result reports. Validation results that are not associated with any individual member, get associated with the model instead.This behavior is a little quirky, but it works well when validation attributes report the member name consistently. In your case, changing the attribute like so should make the behavior more consistent.
- return new ValidationResult(ErrorMessage ?? "Date selected must be greater or equal to today's date.");
+ return new ValidationResult(ErrorMessage ?? "Date selected must be greater or equal to today's date.", new[] { validationContext.MemberName } );
That did the trick. Hope others find this useful, too. Thanks!!
Using Blazor with .NET Core 3.1 Preview.
Have a date picker inside of an EditForm model with a validation message:
This is a custom validation I created to make sure a date in the past is not chosen. The error message displays if incorrect date is chosen. However, if the form if the submit button is clicked, the form does not submit (correct), but the validationmessage for the field disappears.
I added the
<ValidationSummary>
tag up top to test. The error message stays present there even after button clicked. Just not in the Validation Message.