Shared Custom Validation Rules

Shared Custom Validation Rules

Old forum URL: forums.lhotka.net/forums/t/2011.aspx


cultofluna posted on Thursday, December 21, 2006

Hello,

I have a question about using a shared validation rule for multiple properties containing the same information type.

For example:

An order has three registrations of customer company names, on for the customer, the recipient and the invoice customer. The information is available through three different properties CustomerName, RecipientName, InvoiceName. All three need the same validation.

But how should I handle this? When creating a custom validation rule I need to use an interface that has a property with that is also available in the order object. However I have three different propertynames and I don;t want to create three interfaces.

Any thoughts?


cultofluna replied on Thursday, December 21, 2006

For now I have the following solution:

1. Add Rules

ValidationRules.AddRule(ValidateName, "CustomerName");
ValidationRules.AddRule(ValidateName, "RecipientName");
ValidationRules.AddRule(ValidateName, "InvoiceName");

2. ValidateName

        private static bool ValidateName(object target, Csla.Validation.RuleArgs e)
        {
            //***** Use reflection on the target to retrieve the value
            PropertyInfo pi = target.GetType().GetProperty(e.PropertyName);
            string value = (string)pi.GetValue(target, null);
           
            if (value == "Name")
            {
                e.Description = "Invalid Name";
                return false;
            }
            else
                return true;
        }

It works fine! However, it doesn't feel like a good solution. Again any thoughts?

s_tristan replied on Friday, December 22, 2006

What same you confused by? As for me this is not bad solution

ajj3085 replied on Friday, December 22, 2006

That seems fine to me, although you may want to check the PropertyInfo that the PropertyType is actually a string.  Not necessary technically, although it mgiht be easier to locate a problem if you throw another exception instead of letting an InvalidCastException be thrown.

Copyright (c) Marimer LLC