Required string property validation not working

Required string property validation not working

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


lloydm posted on Thursday, May 13, 2010

I’m having trouble getting CSLA to pick up a required string property validation failure.  I have attempted to implement validation using both the declarative approach with Data Annotations and imperatively by overriding the AddBusinessRules() method, but neither method works so far.   In this case, the object’s property contains an empty string just prior to saving (in a winforms app test harness), yet the object has no broken rules and is still marked valid. 

What’s really baffling is that CSLA does properly flag a String Max Length validation failure on the same property!

My business object derives from BusinessBase and implements the Object Factory design for CRUD operations using Entity Framework v.3.5 and the DevArt EF provider for Oracle.  I’m also using CSLA v3.8.2.

The property declaration in my business object looks like this:

[Required(ErrorMessage = " Widget Name is required.")] – Passes validation when property is set to an empty string.

[StringLength(25, ErrorMessage = "The maximum length for Widget Name has been exceeded.")] – Validation fails as expected when property contains > 25 characters.

public string WidgetName

        {

            get { return GetProperty(WidgetName NameProperty); }

            set { SetProperty(WidgetName NameProperty, value); }

        }

Validation also passes for an empty string value if I apply an imperative rule like this:

protected override void AddBusinessRules()

{

ValidationRules.AddRule(Csla.Validation.CommonRules.StringMinLength,

                new Csla.Validation.CommonRules.MinLengthRuleArgs(WidgetNameProperty, 1));

}

 

but fails as expected if the property contains a single character with this imperative rule applied:

protected override void AddBusinessRules()

{

ValidationRules.AddRule(Csla.Validation.CommonRules.StringMinLength,

                new Csla.Validation.CommonRules.MinLengthRuleArgs(WidgetNameProperty, 2));

}

 

Any ideas about what I’m doing wrong?

lloydm replied on Thursday, May 13, 2010

I found the answer: I needed to explcitly call the CheckRules method in the ObjectFactory's create method. 

I left out a small but very important detail: I was attempting to save an object imediately after creation without touching the required property's value, but that meant validation logic did not get invoked since  the property changed event wasn't firing. DOH!  I also noticed that the required string validation did work as expected if I blanked out the property of an existing object.

Copyright (c) Marimer LLC