Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid always returns true

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

like image 847
retsvek Avatar asked Jan 04 '16 03:01

retsvek


1 Answers

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; }
}
like image 163
Vadim Martynov Avatar answered Nov 07 '22 07:11

Vadim Martynov