Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
19 Jan 2016 1  
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. 

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. 

 

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. 

Create basic MVC defalut applicaiton 

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 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.

 

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 return 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;
        }
    }
}

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) 

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. 

<?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.  

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

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here