Validation Rules - Value for Required non-string values

Validation Rules - Value for Required non-string values

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


Joffies posted on Monday, August 18, 2008

Hi

I have a class which containts properties that represent foreign keys within database. These fields are all integers but they are all mandatory fields and the class should force the user to specify/select values for each of these fields. StringRequired doesnt seem to be providing the correct  messaging when fields are mandatory.

What would be the best way/workaround to handle a case where a non-string value is required. I would prefer not to extend the CSLA if possible

 Thanks

IanK replied on Monday, August 18, 2008

Why not use

ValidationRules.AddRule( _

AddressOf Validation.CommonRules.IntegerMinValue, _

New Validation.CommonRules.IntegerMinValueRuleArgs("PropertyName", 1))

Adding FriendlyName argument if required. Your FK probably all default to zero. If you don't like default message you can use something like

 

ValidationRules.AddRule(AddressOf ValidateTownID(Of  <YourObject>), "TownID")

and implement the  Rule as below:

Private Shared Function ValidateTownID(Of T As <YoutObject>)(ByVal target As Object, ByVal e As Validation.RuleArgs) As Boolean

If target.TownID = 0 Then

e.Description = "Please choose a Town"

Return False

End If

Return True

End Function

vdhant replied on Tuesday, August 19, 2008

Hi guys
Not sure if this is what you are after but I came up with this a while ago...

        public static bool NotDefaultValue<T>(object target, RuleArgs e)
        {
            T value = e.ReadField<T>(target, e.PropertyName);
            if (object.Equals(value, default(T)) || String.IsNullOrEmpty(value.ToString()))
            {
                e.Description = string.Format(Resources.ValueRequired, RuleArgs.GetPropertyName(e));
                return false;
            }
            return true;
        }

You don't need to modify CSLA to use this as it is just a static method that you can reference from your own rules repository.
Anthony

Copyright (c) Marimer LLC