Skip to main content

Custom DataAnnotation validation on multiple properties

There are a few cases where you want to be able to validate a property value based on the value of another property. As always there are a bunch of different solutions to this problem, but the cleanest way of doing so is to create a custom DataAnnotaion validation attribute.

It is as easy as creating a class derived from ValidationAttribute and overriding the IsValid-method, but instead of the usual IsValid(object value) we will be overriding the IsValid(object value, ValidationContext validationContext) method.

The ValidationContext contains information about the current object beeing validated and makes it possible to get the values of related properties. By including the related properties and values in our validation class constructor. All in all, it could look like this, even though the validation logic does not really make sense in a real world context it explains the idea pretty good.

[AttributeUsage(AttributeTargets.Property)]
public class CustomValidationAttribute : ValidationAttribute
{
    public string PropertyName { get; private set; }

    public CustomValidationAttribute(string propertyName)
    {
        PropertyName = propertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if(validationContext == null)
            return null;

        var property = validationContext.ObjectType.GetProperty(PropertyName);
        if (property == null)
            return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "Unknown property " + PropertyName));
            
        var propertyValue = property.GetValue(validationContext.ObjectInstance, null);
        if(string.IsNullOrWhiteSpace((string)propertyValue))
            return new ValidationResult(string.Format(CultureInfo.CurrentCulture, PropertyName + " value is null"));

        if (string.IsNullOrWhiteSpace((string)value))
            return new ValidationResult(ErrorMessage);

        return null;
    }
}

When using the attribute we will simply atach it to the property with the related property name as an argument.

[CustomValidation("FirstName", ErrorMessage = "FirstName must not be null or empty")]
public string LastName { get; set; }

Using this technique it is easy to create extremely flexible and advanced validation based on several property values on any object.

Comments

Popular posts from this blog

Binding a HTML-formatted string to a WPF WebBrowser control

Sometimes there is a need to display a HTML formatted string in a WPF application. There are a couple of ways to do this, but the most stright forward is to use a WebBrowser control and the NavigateToString method. This approach has one big flaw, you cannot use binding to a string out of the box, but I found a great solution through Stack Overflow which adds a bindable property to the  WebBrowser  control using  NavigateToString . The following class is all that is needed to add that behavior. A new depencency property named Html is introduced to the  WebBrowser  and the proper change action is performed in the OnHtmlChanged method. public class BrowserBehavior { public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached( "Html", typeof(string), typeof(BrowserBehavior), new FrameworkPropertyMetadata(OnHtmlChanged)); [AttachedPropertyBrowsableForType(typeof(WebBrowser))] public static string GetHtml(WebBrowser bro

Binding Enum with DescriptionAttribute in WPF

Binding an enumeration to a ComboBox can be done in several ways. In most cases you don't want to display the value itself, but a more user friendly description. One common approach is to use the DescriptionAttribute on the Enum values to supply a description for each value.  This is all possible in a very MVVM friendly way. First step is to add the  DescriptionAttribute  to the values of the enumeration. public enum MyValues { [Description("First value")] First, [Description("Second value")] Second } To retrieve the description from the enum we use a simple extension method. This method returns the value of the DescriptionAttribute if it exists, otherwise the string representation of the enum value is returned. public static string GetDescription(this Enum value) { var fieldInfo = value.GetType().GetField(value.ToString()); var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as

Bindable RichTextBox with HTML conversion in WPF

In WPF , the RichTextBox  control is not really like other controls. Due to its flexible nature, there is no built in way of binding a property to the content. In this case, I wanted a simple  RichTextBox  control with a binding to an HTML formatted string to be able to use the built-in formatting features of the  RichTextBox  and allow users to create simple HTML formatted content. First, doing the conversion on-the-fly proved to have major performance issues, so I ended up binding the content to a XAML string. The XAML to HTML conversion can be performed at any time. I created a UserControl with a bindable Text-property. The view contains a  RichTextBox  control. <RichTextBox x:Name="richTextBox" TextChanged="OnRichTextBoxChanged"> The source code for the user control contains the Text property and the methods to handle the binding. public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(st