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:

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

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.

<asp:TextBox ID="txtFirstName" runat="server" />
<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:

[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.

Tweet Post Share Update Email RSS