I am using .NET 6 with Fluent Validation and I have a form with the field:
<form method="post" asp-controller="Product" asp-action="Create" asp-antiforgery="true" autocomplete="off">
<label asp-for="Description">Description</label>
<input asp-for="Description" type="text">
<span asp-validation-for="Description" class="error"></span>
...
<button class="submit" name="button">Create</button>
</form>
The ProductModel
is:
public class ProductModel {
public String Description { get; set; }
// ...
}
And the ProductModel Fluent Validator is:
public class ModelValidator : AbstractValidator<ProductModel> {
public ModelValidator() {
RuleFor(x => x.Description)
.Length(0, 200).WithMessage("Do not exceed 200 characters");
// ...
}
}
When I submit the form I get an error on description if I let it empty:
The Description field is required.
But my validator is not requiring the description.
This happens to all fields. When not filled I get a similar error.
What am I missing, and how can I make it not required?
This seems to be due to a problem relating to model validation changes; specifically in .NET 6. I found a documentation link that can explain it better than me but I'll give a code implementation also: Microsoft docs
builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
//Removes the required attribute for non-nullable reference types.
I've taken this code straight from the MS docs, so if it doesn't fix your issue, there is likely another cause.