Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 976
Dror Weiss Avatar asked Aug 15 '16 20:08

Dror Weiss


People also ask

Why ModelState IsValid is false in MVC?

That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

What exactly does ModelState IsValid do?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


1 Answers

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.

like image 113
Dror Weiss Avatar answered Sep 30 '22 20:09

Dror Weiss