| Microsoft Enterprise Library 5.0 |
| Range Validator |
|
Class Name: RangeValidator<T>
Attribute Name: RangeValidatorAttribute
Configuration tool name: Range Validator
Description
This validator checks that a value falls within a specified range. The range may be either closed, which means it has both a lower and an upper bound specified, or open, which means that it only has one bound specified.
The range validator can be used with any type that implements the IComparable interface. This includes all numeric types and strings. While it is possible, in code, to use this validator with DateTime types, the date time range validator may be a better choice because it allows you to take advantage of attributes and configuration.
Properties
The following table lists the range validator properties. The actual property names displayed in the configuration tools are listed in the table description.
Message Template Tokens
If the message template contains tokens (for example, "{0}"), the validator will replace these tokens with values when the ValidationResult is created. The tokens supported by the range validator are shown in the following table.
|
Token |
Meaning |
|---|---|
|
{0} |
This token represents the value of the object that is being validated. Although it can be useful to show the original value as a part of the validation message, you must be careful to avoid injection attacks by escaping any characters that can be used to attack the system that conveys the message to the user. |
|
{1} |
This token represents the key of the object that is being validated. When the validator is attached to a member of a type such as a property or a field, the key is set to the member name. When the validator is attached to an object, the key is null and the token is replaced by an empty string. |
|
{2} |
This token represents the tag that is specified on the validator instance. If no tag is supplied, the token is replaced by an empty string. |
|
{3} |
The lower bound configured for the validator instance. |
|
{4} |
The lower bound type (Inclusive, Exclusive, or Ignore) configured for the validator instance. |
|
{5} |
The upper bound configured for the validator instance. |
|
{6} |
The upper bound type (Inclusive, Exclusive, or Ignore) configured for the validator instance. |
Example
The following example shows how to use the range validator with attributes to check that the Age property is between 0 and 110, inclusive.
| C# |
Copy Code
|
|---|---|
public class Person
{
[RangeValidator(0, RangeBoundaryType.Inclusive, 110, RangeBoundaryType.Inclusive)]
int Age
{
get
{
return this.CalculateAge();
}
}
// ...
} | |
| Visual Basic |
Copy Code
|
|---|---|
Public Class Person
<RangeValidator(0, RangeBoundaryType.Inclusive, 110, RangeBoundaryType.Inclusive)> _
ReadOnly Property Age() As Integer
Get
Return Me.CalculateAge()
End Get
End Property
' ...
End Class | |