Tuesday, 8 October 2013

How to Pass Custom Error Messages to Data Annotations in Asp.Net MVC?

In previous article we saw "How to Preserve Data Annotations When EDMX File is Recreated?", now in this article I am going to show you "How to Pass Custom Error Messages to Data Annotations in Asp.Net MVC".

It is always better to put all error messages in centralized place instead of hard-coding it. Because of this when we need to change it we change it easily by changing it in centralized place which will reflect all over project instead of manually searching and replacing it all over the project.

For creating this centralized place Right click on project in Solution Explorer, Select Add -> New Folder name it "Resource" or anything meaningful. Then Right click on "Resource" folder, Select Add -> New Item... In Add New Item Dialog go to General Tab -> Resource File name it "ValidationMessages.resx" or anything meaningful. After doing this your Solution Explorer will be like this



In Resource file you can enter your validation messages as Name-Value. For example, error message for FirstName which is required field can be like this and so on..



Now once we define all error messages in Resource file we can easily pass these error messages to data annotations used to validate our model like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using MyResource = CustomizeErrorMessages.Resource;

namespace CustomizeErrorMessages.Models {     public class UserInfo     {         [Required(ErrorMessageResourceType = typeof(MyResource.ValidationMessages), ErrorMessageResourceName = "FirstNameReq")]         public string FirstName { get; set; }         public string MiddleName { get; set; }         [Required(ErrorMessageResourceType = typeof(MyResource.ValidationMessages), ErrorMessageResourceName = "LastNameReq")]         public string LastName { get; set; }     } }
Here, "MyResource" is folder in our project which contains Resource file, "ErrorMessageResourceType" is name of our Resource file which sets the resource type to use for error-message lookup if validation fails and "ErrorMessageResourceName" is name we added in our Resource file which sets the error message resource name to use. During validation process the value related to "ErrorMessageResourceName" is shown.

I hope this article will help you. Please leave comments to improve this article, any suggestion also welcomed.