Data Annotations


You may have found code samples to generate your own Data Annotations handler for Web Forms.  You may have found incomplete or broken examples.  Stop.  Use this instead:

You can do client validation in C# .Net using Data Annotations using this commonly referenced page by Gil Fink:

From this article, it is important to note that the DataAnnotationValidator class MUST be in a Server Control project and referenced as an Assembly.  It is possible that this can be resolved by putting the class in App_Code and removing Assembly from your Register directive:

Create a new Web Server Control Project in your Solution.  Delete the automatically created class file and replace it with the contents from the web page listed above.

Reference the new Assembly/Project in your original Project.


If you try the App_Code technique you will need to change:

<%@ Register TagPrefix=”val” Namespace=”Validator” Assembly=”dotNetValidator” %>

to <%@ Register TagPrefix=”val” Namespace=”Validator” %>

Unfortunately, the App_Code technique didn’t work for me in Visual Studio 2010, which doesn’t want to make an App_code folder.


NOTE:  Here is similar code for client validation in VB:!/2009/08/aspnet-webforms-validation-with-data.html

    I have not tried this code and don’t know if it suffers from the same problem.  Perhaps it doesn’t in


Unfortunately, the C# code doesn’t work because it tests the class Type in the Assembly instead of in the calling Web Project.  This causes an InvalidOperationException error in GetValidatedType. (The returned Type is null.)

This problem was noticed by Alex Ford on stackoverflow: However, the posted solution has the same problem and wasn’t explained in detail.  But is does accurately describe the problem.  And ultimately, this code cannot get the PropertyName validation info necessary.  Stick with the original code.

Data Annotations Solution

So, how do you request a Type check against the calling Assembly?  I found this: Which accurately describes how to dictate the Assembly to search for the Type.

Referring back to Gil’s original article, this syntax was used but not explained.  The calling Assembly , and due to the brief code provided did not state the behaviour or syntax of SourceTypeName.

When using SourceTypeName, you MUST indicate the class name and the calling assembly like this:

<val:DataAnnotationValidator ID=”valID” runat=”server” ControlToValidate=”MyWebControlToValidate” PropertyName=”MyClassVariableToValidate” SourceTypeName=”MyClassToValidateAVariable, MyApplicationAssemblyName” /



<val:DataAnnotationValidator ID=”valID” runat=”server” ControlToValidate=”FirstName” PropertyName=”FirstName” SourceTypeName=”Person, MyWebApp”


For a completely different approach and a complete NuGet package:

To validate a control before submit:

See our Contact Page for more information!