Databases Reference
In-Depth Information
{
return new ValidationResult(
string.Format(“{0} is required”, context.DisplayName),
new string[] { context.MemberName });
}
if (orderDate.Value < DateTime.Today)
{
return new ValidationResult(
string.Format(“{0} cannot be in the past”, context.DisplayName),
new string[] { context.MemberName });
}
return ValidationResult.Success;
}
Each of these two approaches of handling null values in custom validation methods has
its own advantages. You are in the best position to decide what makes sense on your
project; however, you might want to consider starting with the RequiredAttribute as it
offers the easiest and smallest solution for the simple scenarios. You can always change
your mind later if you need to.
Class-Level Validation Methods
You might have noticed that the VerifyOrderDate method actually creates a problem for
orders that have already been placed. Imagine that a customer placed an order on Monday
night, and on Tuesday morning, an employee ships the order and needs to change its
status to Fulfilled. Because the OrderDate is already in the past, the application will not
allow the employee to change the order.
The flaw in the original implementation of the VerifyOrderDate is that the value of
OrderDate is checked separately from other properties of the Order entity. You still want to
make sure that new orders are not submitted with a date in the past, but you also want to
allow employees to update the order status later. One possible way to solve this problem is
to check the OrderDate property only when the OrderStatus is null , which should be the
case for the newly created Order entities before they are marked Submitted.
To perform a validation check that involves more than one property, change the
VerifyOrderDate method so that instead of the OrderDate property value, it validates the
entire Order entity instance. Begin by moving the CustomValidationAttribute from the
OrderDate property to the Metadata class inside of the Order entity:
[CustomValidation(typeof(Order), “ValidateOrderDate”)]
private abstract class Metadata
{
[Required]
[Display(Name = “Order Date”)]
public object OrderDate { get; set; }
}
 
Search WWH ::




Custom Search