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 ?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With