I have two fields and I need to generate an attribute, using Microsoft Enterprise Library validation, so that either or has to have a value, but both can not be null at the same time.
Use a custom validator.
[HasSelfValidation]
public class ValidateMe {
[SelfValidation]
public void ValidateFieldNotNul(ValidationResults validationResults)
{
.. start psudo code
if( xor)
validationResults.AddResult( new ValidationResult("One must not be null",...));
}
}
The Validation Application Block has a PropertyComparisonValidator
which will let you compare one property with another. Unfortunately, this validator only allows a ComparisonType
of: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual
so this doesn't actually help you.
I think you have 2 options:
- Self Validation
- Custom Validator
Self Validation (shown by @Nix) is probably the easiest but would require this to be reimplemented for every scenario where you have that requirement (at least to put the hooks to call a common method).
Creating a custom validator would result in code that could be added to the configuration or attributed directly on entities and that could easily be reused.
A custom validator will definitely be more work but may be worth it if you need the reuse (it can be reused across applications, for example) or prefer that design.