Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Validation in Razor Page

Based on this page I am trying to make a razor page that used fluent validation. It seemed to have checked but I'm not sure why the error message will not display.

Here is what I have done so far:

cshtml.cs:

CreateCommandValidator CreateValidator = new CreateCommandValidator();
var createCheck = CreateValidator.Validate(NewItem);
foreach (ValidationFailure fail in createCheck.Errors)
{
     ModelState.AddModelError(fail.PropertyName, fail.ErrorMessage);
}
return Page();

cshtml:

<label class="col-form-label">Name</label>
<input asp-for="NewItem.Name" type="text" class="form-control mb-2"/>
<span asp-validation-for="NewItem.Name" class="text-danger"></span>

CreateCommandValidator:

RuleFor
     (Item => Item.Name)
     .NotEmpty().WithMessage("The name cannot be empty")
     .Length(1, 100);

The ValidationFailure is able to detect the error message but not sure why it won't be displayed out on the page. Any ideas why? Thanks in advance!

like image 613
Zorev Gnoz Avatar asked Oct 28 '25 15:10

Zorev Gnoz


1 Answers

The ValidationFailure is able to detect the error message but not sure why it won't be displayed out on the page. Any ideas why?

That is because your key name of data-valmsg-for is NewItem.Name.

Your cshtml file below:

<span asp-validation-for="NewItem.Name" class="text-danger"></span>

would generate the html in the browser like below:

<span data-valmsg-for="NewItem.Name" class="text-danger field-validation-valid" data-valmsg-replace="true"></span>

1.The first way,you could change the key name like below:

ModelState.AddModelError("NewItem.Name", fail.ErrorMessage);

2.The second way,if you do not want to add the key name manually,you could install FluentValidation.AspNetCore package and change your code like below:

CreateCommandValidator CreateValidator = new CreateCommandValidator();
var createCheck = CreateValidator.Validate(NewItem);

//AddToModelState(ModelStateDictionary modelState, string prefix);
createCheck.AddToModelState(ModelState, "NewItem");

return Page();
like image 172
Rena Avatar answered Oct 31 '25 11:10

Rena