Posts
208
Comments
1144
Trackbacks
51
EntLib Validation Application Block - Validate a string in ASP.NET

You've created a class like this and all your unit tests pass just fine when you check for null strings or strings greater than 50 characters:

   1:  public class Person
   2:  {
   3:      [NotNullValidator(MessageTemplate="First Name is required.")]
   4:      [StringLengthValidator(50, MessageTemplate="First Name must be 1-50 characters.")]
   5:      public string FirstName { get; set; }
   6:  }

But then when you run it in an ASP.NET application with the PropertyProxyValidator validation control provided by VAB, your business object suddenly shows as valid even though the user left the text box blank.

   1:  <asp:TextBox ID="txtFirstName" runat="server" />
   2:  <vab:PropertyProxyValidator id="firstNameVal" runat="server" ControlToValidate="txtFirstName" 
                                   PropertyName="FirstName" SourceTypeName="WebApplication1.Person"/>

Why is this happening?  The reason is because the ASP.NET infrasture will put an empty string (i.e., a zero-length string) in that property rather than a null.  In point of fact, the validator was not set up correctly to begin with.  The intent is also to prevent an empty string.  So to correct the implementation of the StringLengthValidator, you must give the lower bound of 1 as the first argument as shown here:

   1:  [StringLengthValidator(1, 50, MessageTemplate="First Name must be 1-50 characters.")] 

Additionally, the VAB will allow you to specify whether you want the number specified for the lower/upper bound to be considered inclusvie/exclusive for the range.

posted on Tuesday, June 10, 2008 9:27 PM Print
Comments
Gravatar
# re: EntLib Validation Application Block - Validate a string in ASP.NET
Ramoo
9/8/2008 9:12 AM
Can eplain small example on User control level validation ..
Gravatar
# re: EntLib Validation Application Block - Validate a string in ASP.NET
Steve
9/24/2008 10:10 PM
Ramoo - I'm not sure I totally understand your question about User control level validation. There is nothing inherently different about the validation for a user control when dealing with the enterprise library VAB. With the VAB you are validating the business objects. so that's different than traditional ASP.NET where the "controls are valid." In this case, it's a matter of whether or not the business objects are valid.

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud