FluentValidation icon indicating copy to clipboard operation
FluentValidation copied to clipboard

Submitting form results in InvalidDataOperation "Could not find property named Person on object of type MyProject.BlazorServer.Pages.Person."

Open Bond-Addict opened this issue 1 year ago • 1 comments

Example Code

Parent.razor


<ErrorBoundary Context="ErrorContext" @ref="errorBoundary">
    <ChildContent>
  <EditForm EditContext="EditContext" OnValidSubmit="ValidSubmit" FormName="PersonForm">
      <FluentValidationValidator />
      <InputText @bind-Value="Person.FirstName" />
      <ValidationMessage For="@(() => Person.FirstName)" />
      <br />
      <button style="background:green; padding:1em; color: white;" type="submit">Submit</button>
  </EditForm>
    </ChildContent>
    <ErrorContent>
        <div class="error"><span>An error occurred</span></div>
    </ErrorContent>
</ErrorBoundary>

@code{
    private EditContext EditContext { get; set; }
    public Person Person { get; set; }
    private FluentValidationValidator validator;

    protected override async Task OnInitializedAsync()
    {
         if (Person == null)
             Person = new Person();

        EditContext = new EditContext(Person);
        await base.OnInitializedAsync();
   }
}

Person.cs

namespace MyProject.BlazorServer.Pages
{
	public class Person
	{
		public string FirstName { get; set; } = string.Empty;
		public PersonAddress PersonAddress { get; set; } = new();
	}

	public class PersonValidator : AbstractValidator<Person>
	{
		public PersonValidator()
		{
			RuleFor(p => p.FirstName).Cascade(CascadeMode.Stop).NotEmpty().WithName("FirstName");
		}
	}
}

Image

Image

Image

Problem

ToFieldIdentifier is treating the class name as a property of its self. There is no Person.Person. I even tried to use .WithName() thinking that maybe it just needed to be manually set. This is sample code I'm using to debug a project I inherited which has totally jacked up validation. I assume that maybe there is some dependency that wasnt setup correct, but I can't find any reference to point to what would cause this exception and how to get past it.

Bond-Addict avatar Feb 04 '25 00:02 Bond-Addict

The problem is, that the validator from FluentValidator produces a ValidationFailure that describes a PropertyName that is "Person.FirstName", but the correct PropertyName would be "FirstName". From the current code implementation I cannot spot any problem why FluentValidation would produce such a ValidationFailure.PropertyName. A guess would be

  • a wrong validator/a validator having Person as child is for some reason validating
  • not using OverridePropertyName, because WithName is just for localization

teneko avatar Jun 30 '25 01:06 teneko