Consider the following simple model:
public class TestClass {
[MyRequired(ErrorMessage = "Some error message")]
public int TestVariable { get; set; }
}
This will implicitly add the [Required]
attribute and the rendered html will contain data-val attributes for both [Required]
and [MyRequired]
.
I found 2 possible solutions:
// Solution #1 (.net 5 only)
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
// Solution #2
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Unfortunately the first solution is not available for .net 6 and the second solution doesn't seem to work (propably because int
is a value type and not a reference type?)
Finally I was able to solve this by making the TestVariable
nullable:
public int? TestVariable { get; set; }
Not sure if this is good practice. Is there any way to disable this behavior globally without making everything nullable?