Databases Reference
In-Depth Information
The
MemberNames
property of the
ValidationResult
contains the names of the property or
properties that have invalid values. It is initialized by the
second
argument of the
ValidationResult
constructor. The member names are used by the
DynamicValidator
controls in Dynamic Data web application to determine if their associated column is valid.
This helps to report validation errors coming from custom validation code consistently
with the errors coming from the validation attributes applied declaratively. You can also
avoid hard-coding the property name here and rely on the
MemberName
property of the
ValidationContext
object, which has the name of the property being validated,
OrderDate
in this example.
Following is a test you can use to verify the initial implementation of the
ValidateOrderDate
validation method. Notice how it tries to create an order with a date that was five days
ago. The error is detected by the
ValidateOrderDate
method, and a
ValidationException
is thrown by the
SaveChanges
method:
[TestMethod]
[ExpectedValidationException(MemberName =
“OrderDate”
)]
public void OrderDate_CannotBeInThePast()
{
using (new TransactionScope())
using (var context = new NorthwindEntities())
{
var order = CreateOrder();
order.OrderDate = DateTime.Today.AddDays(-5);
context.Orders.AddObject(order);
context.SaveChanges();
}
}
Handling Null Values
When creating validation methods for nullable properties, check to see if the value is
null
before
performing additional checks. If
null
values are valid according to your business
rules, the method must return
ValidationResult.Success
. Otherwise, you need to decide
if you want to rely on the
RequiredAttribute
or implement this logic in the custom vali-
dation method itself. Relying on the
RequiredAttribute
, as in the previous example,
makes the
CustomValidationAttribute
behave consistently with the declarative validation
attributes.
Placing the entire validation logic for a given property in a single validation method is
typically more verbose; however, it might be easier to follow, especially as the validation
rules get more and more complicated. Here is how you could rewrite this custom valida-
tion method to verify that the
OrderDate
is not in the past
and
that it is not
null
, making
a separate
RequiredAttribute
unnecessary:
public static ValidationResult ValidateOrderDate(
DateTime? orderDate, ValidationContext context)
{
if (orderDate == null)