Exception Message Formatting

All Built-in Validators exceptions can be customized to support localization and more user-friendly messages for GUIs or more technical messages for back-ends. Message formatting can be set either directly on the exception or via the static ValidationAspects.ValidationSettings class.

ValidationSettings.FormatExceptionMessage.GreaterThan(e => string.Format("Value:{0} is not greater than:{1}", e.Value, e.Limit));

You provide a delegate which is passed the exception and returns a string. ValidationException derived exceptions provide data relevant to the specific validation failure and also context on which Instance/Type/Property/Method/Parameter was being validated. You can use the context data to lookup localized strings. For example, if the exception was thrown from a failed property validation, you can use the property name provided by the exception's ValidationContext to lookup a localized property name.

Localization Example
In the following code, both ValidationMessages and PropertyNames are the static classes generated from building a .net Resource File. The value for ValidationMessages.NotNullOrEmpty would be something like {0} is required.
ValidationSettings.FormatExceptionMessage.NotNullOrEmpty(e => string.Format(
The above code assumes the failed validation occured on a property. When using the ValidationContext you should query it to determine the validation target type (Property/Parameter/etc).

Last edited Jan 7, 2009 at 1:50 PM by mikesaunders, version 7


No comments yet.