Validation Block – Conditional Validation

I ran into an interesting problem today.  I am working on a DTO layer for a project at work and we want to use the Ent Lib Validation Block.  This is an ASP.NET application and ideally we will only use the PropertyProxyValidatior on our UI.  For Required fields, it is very straight forward – use the Date/Time, String Length, etc  Validators.  However, the problem comes when we need to evaluate optional (nullable) fields.  We have a couple of use cases:
prop is null or, if not null, only 4 characters in length
prop is null or, if not null, matches email regex
 
According to this post, The Validation Block does not support conditional validation in its attributes.  You can use Self Validation but then you can’t use the PropertyProxyValdiator as described here.  A search of ASP.NET forums also indicates that it can’t be done as described here.
 
To solve this problem, I came up with some adquate workarounds.  For use case #1, use the string length validation and set the base to 0.  For the second use case, put a conditional character ("|") in a reg exexpression.  For example:  [RegexValidator(@"(^.{0,0}$)|(^.{1,4}$)", MessageTemplate = "Need To Be Empty or 1-4 Characters")].  Note that use case #2 works with string.empty and string = "", but not with string = null.  That is ok, I have to make sure the UI calling code defaults to string.empty and it will work.  If anyone know how to do a regex for null, please pass it along (I search some but then gave up)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: