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.36k stars 9.99k forks source link

ValidationMessage disappears on attempted form submit #17110

Closed katiep23 closed 4 years ago

katiep23 commented 4 years ago

Using Blazor with .NET Core 3.1 Preview.

Have a date picker inside of an EditForm model with a validation message:

<EditForm Model="@request" OnValidSubmit="@SubmitRequest">
        <ValidationSummary></ValidationSummary>
        <DataAnnotationsValidator />

<div class="field">
                <MatDatePicker Label="Need Date" @bind-Value="request.RequestedByDate"></MatDatePicker>
                <ValidationMessage For="@(() => request.RequestedByDate)" />
</div>

<MatButton Raised="true" Type="submit">Save</MatButton>
</EditForm>

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.

katiep23 commented 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.");
        }
    }
javiercn commented 4 years ago

@katiep23 thanks for contacting us.

Can you provide a minimal repro project that illustrates the issue?

katiep23 commented 4 years ago

https://github.com/katiep23/ValidationIssue

pranavkm commented 4 years ago

Thanks for the repro project @katiep23. Blazor does two kinds of validation:

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 } );
katiep23 commented 4 years ago

That did the trick. Hope others find this useful, too. Thanks!!