Home > database >  ModelState return false on non required model field
ModelState return false on non required model field

Time:10-25

I have a simple view model as:

public record CreateViewModel
{
    [Required]
    [StringLength(
        250,
        ErrorMessage = "The {0} must be at least {2} characters long.",
        MinimumLength = 5
    )]
    public string Name { get; set; } = string.Empty;

    [StringLength(
        20,
        ErrorMessage = "The {0} must be at least {2} characters long."
    )]
    [Display(Name = "Phone Number")]
    public string AlternateContactPhoneNumber { get; set; } = string.Empty;
}

But for some reason when my controller run the state as:

if (!ModelState.IsValid)
{
    return View(model);
}

It is returning that the Phone Number field is required and I do have not a required data annotation on that model property. Any one knows what is going on?

CodePudding user response:

Probably in your project settings in the .csproj file, the settings are defined as below

<Nullable>enable</Nullable>

If you're using .Net6 and above, this option is enable by default, Which makes string like value types like int and others cannot accept null value by default. To solve this problem, you can set its value to ‍disable or define thestring as nullable as follows:

public string? AlternateContactPhoneNumber { get; set; } = string.Empty;

I recommend reading this article: : Nullable reference types

CodePudding user response:

Use the [ValidateNever] attribute:

[ValidateNever]
public string AlternateContactPhoneNumber { get; set; } = string.Empty;

Indicates that a property or parameter should be excluded from validation. When applied to a property, the validation system excludes that property. When applied to a parameter, the validation system excludes that parameter. When applied to a type, the validation system excludes all properties within that type.

  • Related