Databases Reference
In-Depth Information
public class Product
{
[Required]
public string ProductName { get; set; }
}
The .NET runtime does not invoke the validation attributes automatically. Some code in
your application must detect them and invoke the validation logic explicitly. As you
might recall from the discussion in Chapter 3, “Field Templates,” and Chapter 6, “Page
Templates,” the
DynamicValidator
is responsible for doing this in ASP.NET Dynamic Data
applications, when this control is used in field templates and its
ColumnName
property
specifies the name of the entity property to which validation attributes might have been
applied.
The Data Annotations namespace also provides a helper class, called
Validator
that uses
.NET reflection to validate any object based on the validation attributes applied to its class
and individual properties. Here is how to validate an instance of the Product entity class
we just defined:
var product = new Product();
var context = new
ValidationContext
(product, null, null);
Validator.
ValidateObject
(product, context, true);
The
ValidationContext
object contains information about the object being validated. The
ValidateObject
method passes it to each validation attribute along with the property
value to validate.
ValidationContext
allows implementation of sophisticated validation
logic that is not limited to a single property value. Following is the constructor used in the
preceding example to create this object:
ValidationContext(object instance, IServiceProvider serviceProvider,
IDictionary<object, object> items)
The first parameter,
instance
, is the object being validated. The second,
serviceProvider
,
and third,
items
, parameters of the constructor are used in advanced scenarios, some of
which will be discussed later. For simple cases, they can be
null
.
The
ValidateObject
method of the
Validator
class takes the object to validate as its first
parameter and throws a
ValidationException
for the first validation attribute whose
IsValid
method returns
false
. The actual signature of the
ValidateObject
method is
shown here:
void ValidateObject(object instance, ValidationContext validationContext,
bool validateAllProperties)
Despite what its name implies, the
validateAllProperties
parameter of the
ValidateObject
method actually determines whether all validation
attributes
will be evalu-
ated or only the instances of the
RequiredAttribute
. You want to specify
true
in most
circumstances.