You can use the Tag
property of the ValidationResult
. "The meaning for a tag is determined by the client code consuming the ValidationResults."
If you are using configuration, then you can specify the tag in your configuration file:
<validator lowerBound="0" lowerBoundType="Inclusive"
upperBound="255" upperBoundType="Inclusive" negated="false" messageTemplateResourceName="" messageTemplateResourceType=""
messageTemplate="Oops a warning occurred"
tag="Warning" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="My Validator" />
Or set the Tag with a property:
[StringLengthValidator(5, 50, Ruleset = "RuleSetA", Tag="Warning")]
If you want to do it programmatically, then you will have to create a new validation result since the Tag property is readonly:
ValidationResults newResults = new ValidationResults();
foreach (ValidationResult vr in validationResults)
{
newResults.AddResult( new ValidationResult(
vr.Message, vr.Target, vr.Key, "Warning", vr.Validator, vr.NestedValidationResults ) );
}
Then in the front end you can check the Tag property of the ValidationResult to see if it's a warning:
foreach (ValidationResult vr in validationResults)
{
if (string.Compare(vr.Tag, "Warning") == 0)
{
DisplayWarning(vr.Message);
}
else
{
DisplayError(vr.Message);
}
}
Obviously, you can abstract this much better, aggregate the errors and warnings etc.
UPDATE
We don't have identical requirements to yours but we do something similar. Unfortunately, the only way I know to execute the type of conditional validation you are talking about is to use RuleSets.
What we do is use a naming convention for the RuleSets and construct the RuleSet Names at runtime. If the RuleSet exists then we run the validator. You could do something similar for your warnings. So you could have two RuleSets:
- RuleSet_Salary_Update
- RuleSet_Salary_Update_Warning
And then retrieve a List of Validators based on whether you want to run the warning validation:
public static List<Validator<T>> CreateValidators<T>(bool shoulIncludeWarning, RuleSetType rulesetType)
{
if (shouldIncludeWarning)
{
// Get warning validator if any
}
// Get Default validator (if any)
}
RuleSetType is an enum with different types of rules (e.g. Select, Insert, Update, Delete, PrimaryKey, etc.).