VAB - Integration with ASP.NET using NOTNULLVALIDATOR.

Topics: Validation Application Block
Sep 29, 2008 at 9:05 PM
Edited Oct 1, 2008 at 11:49 AM

I have a Acesso class like this:

[NotNullValidator(Tag = "Nome", MessageTemplateResourceName = "NotNull", MessageTemplateResourceType = typeof(ValidationResource))]
[StringLengthValidator(0, 50, Tag = "Nome", MessageTemplateResourceName = "StringLength", MessageTemplateResourceType = typeof(ValidationResource))]
public String Nome { get; set; }

In my ASP.NET code, I have this:

<asp:TextBox ID="txtNome" runat="server"></asp:TextBox>
<cc1:PropertyProxyValidator Display="None" ControlToValidate="txtNome" SourceTypeName="Model.Acesso" PropertyName="Nome" runat="server"></cc1:PropertyProxyValidator>

OK! It's Validate fine when the txtNome field have more than 50 chars, but when I leave the field blank, I want to NotNullValidator works like RequiredFieldValidator. It's possible?
Oct 7, 2008 at 3:08 PM
First, you need to change the lower bound of the StringLengthValidator to 1 if you want blank fields to be invalid.  This way, you need not have the NotNullValidator.  However, if the user types in spaces, it will be considered valid since it has a length greater than 0.  To handle such cases, you can use the onvalueconvert event of the PropertyProxyValidator.  Its event args has a ValueToConvert property which contains the value being validated.  This way you can check if it's null or empty and set it to empty string if so and modify the ErrorMessage property accordingly.
Jan 29, 2009 at 2:50 AM
Would you please elaborate on checking for spaces wih the ValueToConvert property. Also, a code snippet would be greatly appreciated.
Jan 29, 2009 at 8:40 AM


void PropertyProxyValidator1_ValueConvert(object sender, Microsoft.Practices.EnterpriseLibrary.Validation.Integration.ValueConvertEventArgs e)
if (string.IsNullOrEmpty(e.ValueToConvert.ToString().Trim()))
         e.ConvertedValue = null; // set it to anything that will make it invalid.


If you're not going to use it with a propertyproxyvalidator, you can simply just add the logic of trimming first the value of the property before returning it in the get accessor.

private string name;
public string Name
        return name.Trim();
        name = value;

Sarah Urmenta
Global Technology & Solutions
Avanade, Inc.