Search code examples
c#asp.netvalidationbusiness-objectscustomvalidator

Validate on multiple errors with one CustomValidator


I am trying to figure out how to use Validation on Business Objects.

Until now I have only seen examples on CustomValidator that checks for only 1 error. I have two fields with DateTime input that should check for 3 or more errors. I guess normally I should check on client, then on server, last on database level.

  • If I get an error on a field, I should not be able to leave the field.
  • On the Client Validation this is not an error that should cause an Exception since it's only a user error. But if something goes wrong and the user bypass the Client Validation, the Server Validation should kick an Exception.
  • And last, if i have other e.g. Batch Update work then they should use the Database Validation code. Please correct me if I have missed something fundamental!
  1. `dateFrom` is not empty. (But `dateTo`can be empty)
  2. `dateFrom` is earlier than `dateTo`
  3. `dateFrom` and `dateTo` is within constant `MinDate` and `MaxDate`

So How should my Validation look like, Client, Server and Database?

Thoughts:

Should the validation logic be separated on 3 different places; UI, Code and DataObject(Database)? When it is the exact same code? Seems redundant?

Can I use the same validation method for all three checks? Or do I need to implement 3 code-chunks, and 3 Methods for each, and then how do I list all in the ValidationSummary nicely?


Solution

  • To reduce code duplication and the errors resulting from it, all validation code should be in a single layer - preferably the business layer, as it is in the best position to evaluate the object and determine if it is valid or not.

    However, while that is a theoretical ideal, it is often not pragmatic in real world situations. In a client-server environment, like ASP.NET, you want to duplicate as much of the validation as possible on the client side, in order to reduce round trips to the server. Also, if you have other business procedures (such as batch uploads) that touch your table without going through your business object, you will need to implement the validation in the database as well, to prevent garbage data from being created.

    For validation like in your example, I would create three validation methods on my business object and three CustomValidators - each validator would call the corresponding method on the business object on the server side. I would also code up some JavaScript to run on the client side, so the server side code would just exist to catch non-JavaScript enabled browsers, or maliciously crafted HTTP requests.

    For validation that is difficult to do in JavaScript (i.e. requires the business object), I will not bother with a CustomValidator. Instead, those validations wait until the user presses the submit button, at which point I can use the business object to validate itself and return any errors.