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?
Specifically, the IsValid property is a quick way to check if there are any field validation errors in ModelState. Errors . If you're not sure what's causing your Model to be invalid by the time it POST's to your controller method, you can inspect the ModelState["Property"].
ModelState.IsValid property is an inbuilt property of ASP.Net MVC which verifies two things: 1. Whether the Form values are bound to the Model. 2. All the validations specified inside Model class using Data annotations have been passed.
Inherited IvalidatableObject interface for Model class. Now, implement Validate method to write your custom rules to validate the model. Controller uses ModelState. IsValid to validate the model.
If you're using services.AddMvcCore()
, then you need to explicitly set up your application to perform validation with data annotations:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddDataAnnotations()
/* etc. */;
}
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