Home > OS >  Form field is required even if not defined so
Form field is required even if not defined so

Time:05-02

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" ></span>
    ...
    <button  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 {

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?

CodePudding user response:

Did a little bit of digging, this seems to be due to a problem relating to model validation changes; specifically in ASP 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.

Hope this helps, I've taken this code straight from the MS docs, so if it doesn't fix your issue, there is likely another cause.

CodePudding user response:

Here is very detailed explaintion about this issue in the MC document:

Gets or sets a value that determines if the inference of RequiredAttribute for properties and parameters of non-nullable reference types is suppressed. If false (the default), then all non-nullable reference types will behave as-if [Required] has been applied. If true, this behavior will be suppressed; nullable reference types and non-nullable reference types will behave the same for the purposes of validation.

There are two methods to solve this problem, one global and one partial.

You can set:

builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)

In your Program.cs (.Net6), After using this method, all properties can be null.

Another method is in your model, you can set properties like this:

public class ProductModel {

  public String? Description { get; set; }

  // ...
}

? means this property can be null, in this method, You can specify which properties can be null.

  • Related