CSLA: Make GUIDs required with a custom validation rule

Category:UncategorizedTag: , , :

If you use CSLA and use GUIDs as your unique identifiers you may have need to make them required for a particular object?s property. It isn?t as difficult to do as you might think and I will show you how to accomplish this by writing a custom validation rule.

I have an object that has two properties, a LineNumber and a ControlAccount.  The ControlAccount property is represented by as ComboBox using the Id (GUID) as the SelectedValuePath and the Description as the DisplayMemberPath as displayed by my WPF UI. I don?t want to user to be able to add a record unless they select a Control Account.

guid_not_validated

As you can see the LineNumber is required and I am using the built-in CommonRules.StringRequired rule to add validation to the LineNumber property.

ValidationRules.AddRule(CommonRules.StringRequired, LineItemValueProperty);

So now my problem is that CSLA doesn?t have a GuidRequired rule in its CommonRules class for me to use.  So I will have to write my own.

namespace BusinessLibrary.Validation
{
   public static class CustomRules
   {
      public static bool GuidRequired(object target, RuleArgs e)
      {
         Guid value = (Guid)Utilities.CallByName(target, e.PropertyName, CallType.Get);

         if (value == Guid.Empty)
         {
            e.Description = String.Format("{0} required", RuleArgs.GetPropertyName(e));
            return false;
         }

         return true;
      }
   }
}

Now I can use this custom rule to add a required GUID validation rule to my object on my AccountIdProperty.

ValidationRules.AddRule(CustomRules.GuidRequired, AccountIdProperty);

Now that my rule has been added to my object, my WPF UI will now pickup the new validation rule.

guid_validated

One thought on “CSLA: Make GUIDs required with a custom validation rule”

Comments are closed.

Find me

RSS
Facebook
Twitter
LinkedIn

Disclaimer

The opinions and content expressed here are my own and not those of my employer.