We are trying to use the Foolproof validation annotation [RequiredIf]
to check if an email address is needed. We also created an enum to avoid using a lookup table id in the ViewModel. The code looks like this:
public enum NotificationMethods {
Email = 1,
Fax = 2
}
Then in the ViewModel:
[RequiredIf("NotificationMethodID", NotificationMethods.Email)]
public string email {get; set;}
In this senario we do not get an error when email is unfilled but selected as the notification type. Conversely this works as expected:
[RequiredIf("NotificationMethodID", 1)]
public string email {get; set;}
The only other reference to this I have found is here: https://foolproof.codeplex.com/workitem/17245
Given that your method
NotificationMethodID
is returning anint
, the reason your check is failing is that, in c#, eachenum
is its own type, inheriting fromSystem.Enum
. I.e. if you doYou will see
s
has the value"NotificationMethods"
not"Int32"
.If you try to check the equality of an int with an enum directly, you get a compiler error:
If you box the enum and int values first (which is what happens when they are passed to the constructor of
RequiredIfAttribute
) then there is no compiler error butEquals()
returns false, since the types differ:To check equality of underlying integer values, you can explicitly cast
NotificationMethods.Email
to an integer before boxing:And in the attribute application:
You might also consider using
const int
values instead of enums: