Search code examples
asp.net-mvc-5expressiveannotations

ExpressiveAnnotations.Attributes RequiredIf validation not working


I have the following validation not working and cannot resolve why that is the case?

    [Display(Name = "Bus")]
    [RequiredIf("SelectedWidgetText == 'Referral'", ErrorMessage = "Please select a Vehicle.")]
    public int DepotId{ get; set; }

    public string SelectedWidgetText { get; set; }

I have also tried the following:

[Display(Name = "Bus")]
[AssertThat("SelectedWidgetText == 'Referral'", ErrorMessage = "Please select a Vehicle.")]
public int DepotId{ get; set; }

on the server side, when the modelstate.isvalid method is hit, it returns false and the error message thrown is The DepotId field is required.


Solution

  • just by changing the DepotId to Nullable like the following, the validation started working as expected:

    public int? DepotId{get;set;}

    After reading the documentation, looks like the value types have to be nullable before the data annotation will work on them.