8

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

Joel R Michaliszen
  • 4,164
  • 1
  • 21
  • 28
retsvek
  • 385
  • 4
  • 15

1 Answers1

15

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; }
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
  • Thank you for the extra pair of eyes seeing that! – retsvek Jan 04 '16 at 15:25
  • I did this, but the ModelState.IsValid never kicks in. The request only returns the Data annotations messages, but not my custom return after checking for errors in the ModelState – Miguel Jara Nov 10 '22 at 13:25