Unexcpected Validation Result

Topics: Validation Application Block
Mar 31, 2007 at 3:17 PM
Hallo,
i'm using the following combination of validator:

IgnoreNulls
StringLengthValidator(0, 50, MessageTemplateResourceName = "HomepageLengthMessage", MessageTemplateResourceType = typeof(Properties.Resources))
string Homepage { get; set; }

Wenn the string is null, the validationresult was correctly. Wenn the string is empty or not greater than 50 characters, it's the same.
But when the string is longer than 50 characters, i gave a CompositeOrValidationResult an within 2 ValidationResults. The first is a NotNullValidator with the messageTemplate "The value must be null." and the second validator is a StringLengthValidator. I think the first validation result was not correctly.
Mar 31, 2007 at 11:08 PM
When you apply these validators through attributes, the actual validators that get created are as follows:
  • Or Composite Validator
    • Not Null Validator (Negated = true)
    • String Length Validator

If you were to apply the validators through configuration you would specify them like this, but since the attribute syntax is more limited (eg no support for hierarchies) we added the IgnoreNulls and ValidatorComposition attributes to give you some of the necessary expressiveness.

Anyway, the Or Composite Validator has its own message templates, because reusing the message templates of the nested validators would be misleading, since it's only necessary to fulfil the conditions of just one of the nested validators. So you should use a message template in the Or Composite Validator saying something like "The value must be null or no longer than 50 characters". As you discovered you can programatically look at the nested ValidationResults if you care which nested validators failed.

IIRC, When you are using attributes, specifying a message template on the IgnoreNulls or ValidatorComposition attributes will result in that being applied to the implicitly created Or Composite Validator.

HTH
Tom