views:

133

answers:

2

I have an field, Address2, which is optional. Thus if it is null, no validation rules apply. However, if a value exists, its length cannot be greater that 255 characters.

I have been toying with:

<StringLengthValidator(0, RangeBoundaryType.Inclusive, 255, RangeBoundaryType.Inclusive, MessageTemplate:="Address 2 can be between 0 and 255 characters in length.", Ruleset:="MyRules")> _

But if it's not present, I still get an error.

Any suggestions?

Thank you.

A: 

You should decorate the property with an IgnoreNullsAttribute:

<IgnoreNulls>
<StringLengthValidator(0, RangeBoundaryType.Inclusive, ... )>
public string Address2 { get; set; }
Steven
Still no go on that one. If Address2 is not null (or empty), the length should be between 5 and 255 chars, which I'm familiar with, but not the appropriate property syntax, as IgnoreNulls is not working. I found a discussion here: http://www.codeplex.com/entlib/WorkItem/View.aspx?WorkItemId=8595 suggesting IgnoreNullsOrEmpty.
ElHaix
A: 

The following attributes will require that the string length be between 5 and 255 characters if a value is specified (including empty string) or that the string is null.

<ValidatorComposition(CompositionType.Or, Ruleset:="MyRules", MessageTemplate:="Address line 2 must be between 5 and 255 characters")> _
<StringLengthValidator(5, 255, Ruleset:="MyRules")> _
<NotNullValidator(Negated:=True, Ruleset:="MyRules")> _
Public Property Address2() As String


So all Address2 strings must be between 5 and 255 characters unless Address2 is null.

Tuzo