DataAnnotations - Multiple Acceptable Values
-
I was looking into using data annotations to help validation on one of my classes. However, in my class there is a property called
CommandFamily
which is aByte
. This property must have a value of 0x01 - 0x07 or 0xFF. I have already applied theRequired
attribute and was looking into using theRange
. However theRange
attribute can only accept a minimum and maximum value and you cannot apply more then oneRange
attribute. I checked on MSDN and I don't see any other attribute that will allow you to apply a list of values. I would really like to avoid having to change the acceptable values for theCommandFamily
property if possible. Is there any way data annotation attribute, or combination, that will allow me to specify a range of acceptable values, instead of just a single range? Thanks in advance for any assistance or guidance on this.A black hole is where God tried to divide by zero. There are 10 kinds of people in the world; those who understand binary and those who don't.
-
I was looking into using data annotations to help validation on one of my classes. However, in my class there is a property called
CommandFamily
which is aByte
. This property must have a value of 0x01 - 0x07 or 0xFF. I have already applied theRequired
attribute and was looking into using theRange
. However theRange
attribute can only accept a minimum and maximum value and you cannot apply more then oneRange
attribute. I checked on MSDN and I don't see any other attribute that will allow you to apply a list of values. I would really like to avoid having to change the acceptable values for theCommandFamily
property if possible. Is there any way data annotation attribute, or combination, that will allow me to specify a range of acceptable values, instead of just a single range? Thanks in advance for any assistance or guidance on this.A black hole is where God tried to divide by zero. There are 10 kinds of people in the world; those who understand binary and those who don't.
The simplest option would probably be to use the
CustomValidation
attribute[^] to call aPublic Shared
method to validate the value.Public NotInheritable Class CommandFamilyValidator
Public Shared Function Validate(ByVal commandFamily As Byte) As Boolean
Return commandFamily = &H01 _
OrElse commandFamily = &H07 _
OrElse commandFamily = &HFF
End Function
End Class
...
<CustomValidation(GetType(CommandFamilyValidator), "Validate")> _
Public Property CommandFamily As Byte
...Alternatively, you could create your own validation attribute by inheriting from the
ValidationAttribute
class[^]. This SO answer[^] has an example.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer