asp.net core 2.0 model validation not validating data
Asked Answered
P

3

8

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?

Powys answered 11/8, 2018 at 11:16 Comment(7)
You need to set the Id to nullable else the value will be defaulted to 0 even if the client don't send an Id in the request.Westnorthwest
I've copied your code exactly, and I can't reproduce your problem. One thing to note, however: Required checks that a value won't be null, an empty string, or whitespace. In your case, Id is a non-nullable int, so that will always provide a value.Slave
Alright I got the case for required as it should be nullable to work. But what about the Range attribute, why it's not working?Powys
@AliShahzad, same for me, Range works as expected - when Id is outside of range or not supplied (zero by default) i get a 400 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
@Redcoat But it's not working for me which I guess I'm missing somethingPowys
Share us the project which coudl reproduce your issue.Ectoderm
@AliShahzad Were you ever able to figure out the issue?Miraculous
K
12

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. */;
}
Kellykellyann answered 1/3, 2019 at 22:59 Comment(1)
Thanks @Collin that fixed a similar problem that we were experiencing.Robbinrobbins
E
1

I used the same model property that you defined in the model and facing the same issue. I made one change in the property and defined the DataMember attribute on the property like:

[Required(ErrorMessage = "Id is required")]
[Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
[DataMember(Name = "Id")]
public int Id { get; set; }

It's working as expected, validating the range values. Try this, hope it will resolve the issue that you are facing.

Expectorate answered 2/3, 2019 at 5:10 Comment(0)
N
1

I also fought with this problem and what helped in my case was adding this in ConfigureServices:

services.AddMvc(opt=> {
    opt.AllowValidatingTopLevelNodes = true;
});

Just be carefull about the outcome - if you want to get automatic BadRequest you have to use [ApiController] attribute. Otherwise you have to check ModelState.IsValid property.

Nocturnal answered 9/9, 2019 at 8:5 Comment(2)
AllowValidatingTopLevelNodes is obsolete from 2.2 and not found in 3.1. Any idea how to use it in 3.1?Otha
According to github.com/dotnet/AspNetCore.Docs/issues/… validation of top level nodes is enabled by default when using any of mentioned services.Nocturnal

© 2022 - 2024 — McMap. All rights reserved.