I've seen a lot of posts about IsValid always being true but none of them have helped me solve this problem. I'm also seeing this problem in ASP.NET 4 using MVC5. So clearly I'm missing a step somewhere.
Controller method:
public IHttpActionResult Post([FromBody]ValuesObject value)
{
if (ModelState.IsValid)
{
return Json(value);
}
else
{
return Json(ModelState);
}
}
ValuesObject Class:
public class ValuesObject
{
[Required]
public string Name;
[Range(10, 100, ErrorMessage = "This isn't right")]
public int Age;
}
Body of the POST:
{
Age: 1
}
ModelState.IsValid is true.
But I would expect both the Required and Range validations to fail.
What am I missing??
Thanks,
Kevin
You can't use fields in your model. it's one of general conditions for your validation.
In ASP.NET Web API, you can use attributes from the System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your model.
Replace it with properties and all will work fine:
public class ValuesObject
{
[Required]
public string Name { get; set; }
[Range(10, 100, ErrorMessage = "This isn't right")]
public int Age { get; set; }
}
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