views:

514

answers:

1

I am using custom view model classes as DTO objects to hold data for display on my View pages. I have applied validation via the DataAnnotations library to perform server side validation on the properties of these classes. Here is a simple example:

[DisplayName("Customer Account Id")]
[Required(ErrorMessage = "* Account Number is required")]
[StringLength(16, ErrorMessage = "* Account Number must be 16 characters in length", MinimumLength = 16)]
public string CustomerAccountId { get; set; }

If someone submits a search and this field does not come through or comes through at a length that is not 16, validation fails, and an error message is displayed on the page via the ValidationMessage HtmlHelper:

<%= Html.ValidationMessage("CustomerAccountId")%>

Now I need to add the ability to search by account id OR a combination of First/Last name. My question is this:

How do I apply conditional validation? If I submit a search with First/Last name, I don't want validation to fail because an account number was not passed through as well. I found this link, which shows how to implement a custom validator, but it seems like this applies to 1 property. How do I pass an entire object model through, and pass back the appropriate validation error messages to the appropriate fields to be displayed on the page? Is this possible?

A: 

You can implement IDataErrorInfo. (The class name is misspelled in the article title, but the code is right.)

Craig Stuntz