Data Annotations

I discovered data annotations while I was learning ASP.NET Web Forms Model Binding sometime back. From a little reading, I got to know that it was first introduced in Silverlight and also available on ASP.NET MVC - so it is really nothing new.

Basically, it is a library of .NET Attributes from the System.ComponentModel.DataAnnotations namespace that can help make validation tasks simpler. Take for example if we want the Name property of our User entity to be required, we would go all the way to do something like this to validate it in our code:

if (string.IsNullOrWhiteSpace(user.Name))
{
    throw new ApplicationException("Name cannot be blank.");
}

But with data annotations, all we need to do is just decorate the Name property with a validation attribute, for example the RequiredAttribute.

[Required]
public string Name { get; set; }

Any violation to the validation you applied will be given an error message. The default error messages are somewhat very basic. Fortunately, you can customize the error messages:

[Required(ErrorMessage="Please enter your name. It is very important.")]
public string Name { getset; }

You can apply multiple attributes to the properties at once.

[Required]
[EmailAddress]
[MinLength(5, ErrorMessage = "Email must be atleast 5 characters.")]
[MaxLength(255, ErrorMessage = "Email must not exceed 255 characters.")]
public string Email { get; set; }

If you can't find a validation attribute for something that you need to validate, you can always use the RegularExpressionAttribute. Here's an example:

[RegularExpression("^60.*$", ErrorMessage="Mobile No. must start with prefix 60.")]
public string MobileNo { get; set; }

There are many validation attributes provided out-of-the-box, you can get a list of them here.

To hook it up to the ASP.NET Web Forms controls, specify the entity as the ItemType of the control
(i.e. FormView) and also declare a ValidationSummary to display the error messages.

<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="FormFields" ForeColor="Red" />

<asp:FormView ID="userForm" ItemType="Sample.Entities.User" runat="server" DefaultMode="Insert" InsertMethod="userForm_InsertItem">

In the code-behind, call the TryUpdateModel method:

public void userForm_InsertItem()
{
    var user = new User();
    TryUpdateModel(user);

    if (ModelState.IsValid)
    {
        // Do your stuff...
    }
}

That's all to it. You can check the ModelState.IsValid property to determine the next course of action. If there are any validation errors, they will be displayed in the ValidationSummary automatically.


Now isn't that cool? :)

No comments:

Post a Comment

Popular Post