Introduction
In this post we will discuss custom validation in MVC using data annotation. In addition, instead of hard coding error messages we will get custom error messages from a XML file. This XML file will support multilingual and multi geographical messages.
There are scenarios when data validations provided by MVC are not sufficient to meet the requirements and we need custom validation messages, like to show custom error messages based on language and geography.
To showcase the code base, we will utilize default MVC web application provided by Visual Studio 2013 and will add code required to customize validation in registration page available in that.
Create basic MVC default application
Open Visual Studio 2013 IDE, and create a new project as shown below:

Select ASP.NET Web Application:

Select MVC as template and click on OK, no need to change any other option.

This will give you a readily available small application which we can use as a base to add our code. I have used a registration page for creating custom validation.
Using the code
Now create two custom validators, one for custom required validation, and another for custom special char not allowed validation.
Below are the new class files we will be creating to achieve this.

Create a new folder “Helpers” inside existing Models folder, we will use this folder to keep all new class files we will create.
Add a class RequiredValidation. All of the validation annotations like Required, EmailAddress are ultimately derive from the ValidationAttributebase class. So we will also derive RequiredValidation class also from ValidationAttributebase.
Here IsValid function, which is provided by the base class, is overridden to create a custom Validation. It take two parameters, first one is ValidationContext which will give display name of the property to be validated and second one is value to be validated.
Here in this validation we are checking whether value is Null or empty, if yes it returns a custom message. This custom message in this example case of "Display Name of the control - <message from resource file>".
To get the custom message, a function GetResourceString is used, which is explained at the end, it took four parameter Resource file path, resource key, language and state.
ValidationResourceFile in below code contain path of the XML file where all error messages will be added. Structure of this XML file and the function GetResourceString are explained at the end.
- namespace WebAppCustomValidation.Models.Helpers
- {
- public class RequiredValidationAttribute: ValidationAttribute
- {
- public static string ValidationResourceFile = "/App_Data/ValidationMessages.xml";
- public RequiredValidationAttribute(): base("{0}") {}
- protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
- if (value == null || value.ToString().Trim() == "")
- {
- return new ValidationResult(FormatErrorMessage(validationContext.DisplayName) + " - " + Models.Helpers.ValidationHelper.GetResourceString(ValidationResourceFile, "Required", "EN", "XY"));
- }
- return ValidationResult.Success;
- }
- }
- }
ValidationResourceFile as above contain path of the error XMl file. (This file path I am passing to the function in all validation rule, if this is one file only throughout the project you can keep it in Validation helper also).
Here the value, coming from the control, is checked for any special character set as not allowed. If any such character is found in the value a custom error text return as error message. This custom error message as above is fetched from error XML file based on key, language and state. (GetResourceFunction has been used for this purpose, explained later)
Copy Code- namespace WebAppCustomValidation.Models
- {
- public class CharNotAllowedAttribute: ValidationAttribute
- {
- public static string ValidationResourceFile = "/App_Data/ValidationMessages.xml";
- private readonly string _invalidChars;
- public CharNotAllowedAttribute(string invalidChars): base("{0}")
- {
- _invalidChars = invalidChars;
- }
- protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
- if (value != null) {
- for (int i = 0; i < _invalidChars.Length; i++)
- {
- if (value.ToString().Contains(_invalidChars[i]))
- {
- return new ValidationResult(FormatErrorMessage(validationContext.DisplayName) + " - " + Models.Helpers.ValidationHelper.GetResourceString(ValidationResourceFile, "Invalid_Chars", "EN", "XY"));
- }
- }
- }
- return ValidationResult.Success;
- }
- }
- }

Manav PandyaPosted Sep 30, 2016, 10:26 AM
Nice share sir ...
SubashPosted Sep 15, 2016, 1:08 AM
Useful one
Jaco ZwartsPosted Feb 11, 2016, 12:09 PM
Thank you for sharing this!
Nishant PradhanPosted Feb 6, 2016, 2:49 AM
Nice one
Suraj PantPosted Feb 2, 2016, 1:24 AM
Thanks Shubham
Shubham KumarPosted Feb 2, 2016, 1:06 AM
nice
Jaipal ReddyPosted Feb 2, 2016, 12:35 AM
Nice one sir. .
Mohammed IbrahimPosted Feb 1, 2016, 2:13 PM
nice
Sibeesh VenuPosted Feb 1, 2016, 1:11 AM
Nice Share
Ankit BansalPosted Feb 1, 2016, 12:38 AM
nice one..
Suraj PantPosted Feb 1, 2016, 12:24 AM
Thanks Debasis.
Debasis SahaPosted Jan 31, 2016, 11:24 PM
Good One..
Santhakumar MunuswamyPosted Jan 31, 2016, 12:36 PM
Thanks for nice article
Nanddeep NachanPosted Jan 31, 2016, 10:24 AM
Nice share
Guest UserPosted Jan 31, 2016, 9:14 AM
thanks very much for the nice write-up, I'm liking asp.net more and more the better I understand mvc, so thanks for sharing
Suraj PantPosted Jan 31, 2016, 4:09 AM
Thanks Arul
Arul RPosted Jan 31, 2016, 3:51 AM
Nice share
Jaco ZwartsPosted Jan 31, 2016, 3:46 AM
Nice Article Thanks for sharing