I am using ASP.NET Core 2.0 default model validation and it seems not working with the ModelState.IsValid
always true despite having wrong data in model.
[HttpPost("abc")]
public async Task<IActionResult> Abc([FromBody]AbcViewModel model)
{
if (!ModelState.IsValid) { return BadRequest(ModelState); }
...
}
public class AbcViewModel
{
[Required(ErrorMessage = "Id is required")]
[Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
public int Id { get; set; }
public bool Status { get; set; }
}
When I post data from Angular app, the values are mapping to model correctly but if Id
is "0" or less than 100, both the Required
and Range
validators aren't working and ModelState.IsValid
is always true. What I am missing?
Required
checks that a value won't benull
, an empty string, or whitespace. In your case,Id
is a non-nullableint
, so that will always provide a value. – SlaveRange
works as expected - whenId
is outside of range or not supplied (zero by default) i get a400 BadRequest
POST /api/values/abc HTTP/1.1 Host: localhost:61154 Content-Type: application/json Cache-Control: no-cache Postman-Token: 62024574-776a-4e1b-93b7-6a7bb78ecfca { "Id": 1 } 400 Bad Request {"Id":["Invalid Id"]} – Redcoat