Search code examples
c#asp.net-web-api2expressiveannotations

RequiredIf not working for int property


I'm using ExpressiveAnnotations to have some validation on my properties. Now, I'm facing a problem where I'm not able to validate a property of type int:

public class MyModel {

    public string AorB { get; set; }

    [RequiredIf("AorB == 'B'")]
    public string Foo { get; set; }

    [RequiredIf("AorB == 'B'")]
    public int Bar { get; set; }
}

My controller

public class MyController : ApiController
{

    public IHttpActionResult Post(MyModel myModel)
    {
        if(ModelState.IsValid)
        {
            // do something
            return Ok();
        }

        return BadRequest("To bad");
    }
}

When I POST: {"AorB" : "B", "Bar" : 1} I get a message that "Foo is required because of AorB == B" and the system returns BadRequest

When I POST: {"AorB" : "B", "Foo" : "foo"} I don't get a message and the system returns Ok.


Solution

  • Ok, The reason that it was not validating is because it should be int? so the model looks like this:

    public class MyModel {
    
        public string AorB { get; set; }
    
        [RequiredIf("AorB == 'B'")]
        public string Foo { get; set; }
    
        [RequiredIf("AorB == 'B'")]
        public int? Bar { get; set; }
    }