Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core 2.0 model validation not validating data

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?

like image 704
Ali Shahzad Avatar asked Aug 11 '18 11:08

Ali Shahzad


People also ask

How do I know if a model is valid or not?

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"].

What does ModelState IsValid validate?

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.

How do I check if a web API model is valid?

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.


1 Answers

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. */;
}
like image 89
Collin K Avatar answered Sep 20 '22 04:09

Collin K