Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Validation Attribute for Enum without Zero Value

0.00/5 (No votes)
10 Mar 2016 1  
When binding to an Enumeration, the Required Attribute does not work if the enumeration does not have a zero value. This validator does work.

Introduction

I worked on a project with a lot of binding of ComboBoxes to enumerations, and sometimes these enumerations did not have an enumeration of zero defined, and that caused problems when using the ComponentModel DataAnnotations RequiredAttribute for new records. The RequiredEnumAttribute ValidationAttribute solved the problem.

The Code

The code is extremely simple and only has to inherit from the RequiredAttribute and override the IsValid method:

public class RequiredEnumAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        var type = value.GetType();
        return type.IsEnum && Enum.IsDefined(type, value);;
    }
}

Because of this design, every capability of the RequiredAttribute is available for this ValidationAttribute.

The Sample

On the bound value for both these cases, the Enum has not been set, so it is at the default value, however, there is no value assigned to 0:

public enum TestEnums { One = 1, Two = 2, Three = 3 }

In the in the upper ComboBox, a property of TestEnums Type is bound to the SelectedItem DependencyProperty, and the property uses the Required decorator. The next ComboBox is identical, except that it is has the RequiredEnumAttribute decorator.

Since the DataContext is a new record and no values have been assigned, the default is 0 for the bound enumeration even if there is enumeration defined for 0. This may acatually good since the develolper may not want to have an initial value set, requiring the user to actually set a value before continuing. The other option is to use a Nullable enumeration. The advantage of Nullable is that a normal Required decoractor can be used, but then have to ensure that a non-Nullable enumeration base value is appropriately handled.

In the above picture you can see two addtional ComboBox's bound to an enumeration that has the zero value defined. Both have the [Required] attribute in the ViewModel. In the third ComboBox what happens when there is a default value of zero has been defined, and the enumeration is left at its default value. The last ComboBox is bound to a Nullable, and the enumeration has a 0 value defined. The default value in this case is Null, so the Required attribute generates an error.

History

  • 03/10/2016: Initial version
  • 08/02/2016: Changed name to RequiredEnumAttribute

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here