dror
dror

Reputation: 3946

ModelState.IsValid always true, regardless of DataAnnotations attributes

I'm using the new MVC6 framework with Visual Studio 2015, and suddenly all my Data Annotations stopped working. All of them, without me changing the code.

public sealed class RegisterUser
{
    [Required(ErrorMessage = "required")]
    [RegularExpression(@"^((.|\n)*)$", ErrorMessage = "regex")]
    [StringLength(32, MinimumLength = 3, ErrorMessage = "length")]
    public string Name { get; set; }

    ...
}

And

[Route(Address + "/membership")]
public class MembershipController : Controller
{
    // POST [address]/membership/register
    [AllowAnonymous]
    [HttpPost("Register")]
    public IActionResult Register([FromBody]RegisterUser model)
    {
        // Validate the input model.
        if (model == null)
            return ...

        if (!ModelState.IsValid)
            return ... 

        // Always get HERE 
    }
}

Why, on earth, do I pass the "ModelState.IsValid" test (it always evaluates to true) ?

For example, I'm passing Name="x", and it still evaluates to true. As if the annotations aren't there.

Does it relate to using MvcCore ?

Upvotes: 5

Views: 4667

Answers (3)

Peter L
Peter L

Reputation: 3343

{ get; set; } Required
I know the OP has NOT made this error but I have just wasted a number of hours...

Need to use public string Name { get; set; } and not public string Name;

I'm using ASP Core 3.1.

Upvotes: 0

Bellash
Bellash

Reputation: 8184

Was experiencing the same issue and commented this following line of code

  services.AddControllersWithViews(options => {
            // options.ModelValidatorProviders.Clear();
        }).AddRazorRuntimeCompilation();

I don't remember why I added this line of code...

Upvotes: 0

dror
dror

Reputation: 3946

Frustrating as it is, I forgot that changing to 'core' project strips out many of the common features. And so, in Startup.cs, add

  • services.AddMvc()

or

  • services.AddMvcCore().AddDataAnnotations()

Depending on your usage.

Upvotes: 17

Related Questions