Click here to Skip to main content
15,867,330 members
Articles / Web Development / HTML

MVC – Custom Validation (get conditional error messages from XML file)

Rate me:
Please Sign up or sign in to vote.
4.67/5 (6 votes)
19 Jan 2016CPOL4 min read 15.4K   1   10   8
Create custom validation in ASP.Net MVC application through data annotation and get customized error messages from XML file.

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. <o:p>

There are scenarios when data validations provided by MVC is not sufficient to meet the requirements and we need custom validation messages, like to show custom error messages based on language and geography. <o:p>

 

To showcase the code base, we will utilized default MVC web application provided by visual studio 2013 and will add code required to customize validation in registration page available in that. <o:p>

Create basic MVC defalut applicaiton 

Open Visual Studio 2013 IDE, and create a new project as shown below: 

Image 1

Select ASP.Net Web Application:  

Image 2

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

Image 3

This will give you a readily available smallapplication which we can use as a base to add our code. I have used registration page for creating custom validation.

Using the code

Now create two custom validator, one for custom required validation, and one for custom special char not allowed validation.

Below are the new class files we will be creating to achive this.

Image 4

 

Create a new folder “Helpers” inside existing Models folder, we will use this folder to keep all new class files we will create. <o:p>

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.<o:p>

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.<o:p>

Here in this validation we are checking whether value is Null or empty, if yes return a custom message. This custom message in this example case of "Display Name of the control - <message from resource file>". <o:p>

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. <o:p>

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.<o:p>

 

C++
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;
        }
    }
}

Similarly for not allowing some specific special character, create a new class CharNotAllowed. Here characters not allowed will be passed with data annotation itself and will be taken in _invalidchars as shown below. 

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) 

C++
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;
        }
    }
}

 

Now create another class ValidationHelper.cs. This will be used to get error message against a key, based on language and state provided.

Before adding this class let’s have a look in to the error XML file, we have used in this code example. Please refer below XML sample, here expression tag contain all conditions we need to check, in our case we are using language and state, if require we can add more and further customize messages.

Any ValidationMessage can have multiple TargetRules for different keys. Function GetResourceString fetch the required <Message> from below XML based on language and state. 

C++
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfMessages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ValidationMessage ID ="Invalid_Chars">
    <TargetableRules>
      <TargetableRule>
        <Expression>
          <lang>EN</lang>
          <state>AB,CD</state>
        </Expression>
        <Message>Invalid charactors found! (AB,CD)</Message>
      </TargetableRule>
      <TargetableRule>
        <Expression>
          <lang>EN</lang>
          <state>BC,DF,XY</state>
        </Expression>
        <Message>Invalid charactors found! (BC,DF,XY)</Message>
      </TargetableRule>
      <TargetableRule>
        <Expression>
          <lang>FR</lang>
          <state>AB,CD,BC</state>
        </Expression>
        <Message>Invalid charactors found! [fr] (AB,CD,BC)</Message>
      </TargetableRule>
    </TargetableRules>
  </ValidationMessage>
<ValidationMessage ID ="Required">
    <TargetableRules>
      <TargetableRule>
        <Expression>
          <lang>EN</lang>
          <state>AB,DF,XY</state>
        </Expression>
        <Message>Field required! (AB,DF,XY)</Message>
      </TargetableRule>
      <TargetableRule>
        <Expression>
          <lang>FR</lang>
          <state>AB,CD</state>
        </Expression>
        <Message>Invalid charactors found! [fr] (AB,CD)</Message>
      </TargetableRule>
    </TargetableRules>
  </ValidationMessage>
</ArrayOfMessages>

Now add function GetResourceString, inside ValidationHelper class.

Load XML from the path in xDocument, and through a LINQ query fetch ValidationMessage node for given key. Next, through another LINQ query get the element where language and state are matching. 

This will provide the node filtered for given key, language and state. Fetch value of Message element and convert that in a string and return.  

C++
namespace WebAppCustomValidation.Models.Helpers
{
    public class ValidationHelper
    {
        public static string GetResourceString(string resourceFile, string resourceKey, 
                                              string lang, string state)
        {
            string retValue = string.Empty;
            XDocument xDoc = XDocument.Load(resourceFile);
            
            var MessageResource = from m in xDoc.Descendants("ValidationMessage")
            .Where(r => (string)r.Attribute("ID") == resourceKey)
            select m;
            
            var Msg = from m in MessageResource.Descendants("Expression")
            .Where(r => (string)r.Element("lang").Value == lang 
                        && (bool)r.Element("state").Value.Contains(state) == true)
            select m.Parent;
            foreach (XElement element in Msg.Descendants("Message"))
            {
                retValue = element.Value.ToString();
            }
            return retValue;
        }
    }
}

use new validation methods, as annotation

C++
public class RegisterViewModel
    {
        [RequiredValidation]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
        
        [RequiredValidation]
        [CharNotAllowed("@#")]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }


Sample Code

Code sample is attached with the article, please refer to the "Helpers" folder insode Models. This folder contain required classes. Sample errro XML is available in App_Data folder.    

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
IBM India
India India
A Development Consultant, Solution Development Lead and Architect with 13 years of experiences in envisioning, planning, designing, development and delivery methodologies using Microsoft technology.

Comments and Discussions

 
Questionno link to download the sample code Pin
Member 122277076-Dec-18 20:10
Member 122277076-Dec-18 20:10 
QuestionInteresting article Pin
fidratp23-Jan-16 3:25
fidratp23-Jan-16 3:25 
QuestionNice article Pin
Santhakumar M20-Jan-16 4:17
professionalSanthakumar M20-Jan-16 4:17 
AnswerRe: Nice article Pin
Suraj Pant20-Jan-16 6:35
Suraj Pant20-Jan-16 6:35 
GeneralRe: Nice article Pin
Santhakumar M20-Jan-16 17:36
professionalSanthakumar M20-Jan-16 17:36 
GeneralVeryhelpful topic Pin
vijaysutaria20-Jan-16 0:44
vijaysutaria20-Jan-16 0:44 
GeneralRe: Veryhelpful topic Pin
Suraj Pant20-Jan-16 6:34
Suraj Pant20-Jan-16 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.