Custom Validation Attribute

Custom Validation Attribute in asp.net MVC:

In this article, I will discuss creating a Custom Validation Attribute in ASP.NET MVC.

Please read the Range Attribute article before proceeding to this article as I am going to use the same example that we created in our previous article.

At the moment, any value outside the range of “01/01/1970” and “01/01/2005” for DateOfBirth filed will raise a validation error. 

[Range(typeof(DateTime), "01-01-1970", "01-01-2005",
                    ErrorMessage = "Date of Birth Must be between 01-01-1970 and 01-01-2005")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
    get;
    set;
}

But, let’s say, we want the end date to be today’s date instead of the hardcode “01/01/2005” value. To achieve this we would be tempted to use DateTime.Now.ToShortDateString() as shown below.

[Range(typeof(DateTime), "01-01-1970", DateTime.Now.ToShortDateString(),
                    ErrorMessage = "Date of Birth Must be between 01-01-1970 and Current Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
    get;
    set;
}

At this point, if you compile, we will get the following error –

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

To fix this, we can create a custom DateRangeAttribute. Here are the steps

1. Right-click on the project name in solution explorer, and add “Common” folder.

2. Then Right-click on the “Common” folder and add a class file with name =DateRangeAttribute.cs

3. Copy and paste the following code in DateRangeAttribute.cs class file. 

using System.ComponentModel.DataAnnotations;

namespace DataAnnotationInMVC.Common
{
    public class DateRangeAttribute : RangeAttribute
    {
        public DateRangeAttribute(string minimumValue)
            : base(typeof(DateTime), minimumValue, DateTime.Now.ToShortDateString())
        {

        }
    }
}

4. Finally, decorate the “DateOfBirth property with our custom DateRangeAttribute as shown below.

Notice that, we are only passing the minimum date value. Maximum date value will be today’s date. Please note, DateRangeAttribute is present in MVCDemo.Common namespace.

[DateRange("01/01/2000", ErrorMessage = "Date of Birth Must be between 01-01-1970 and Current Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
    get;
    set;
}
Let’s now look at another example of creating a custom validation attribute. 

Let’s say our business rules have changed, and the DateOfBirth property should allow any valid date that is <= Today’s Date. This means, there is no minimum value restriction and the maximum value should be less than or equal to Today’s date. To achieve this, let’s add another custom validation attribute. Here are the steps

1. Right-click on the “Common” folder and add a class file with name = CurrentDateAttribute.cs

2. Copy and paste the following code in CurrentDateAttribute.cs class file. 

using System.ComponentModel.DataAnnotations;
namespace DataAnnotationInMVC.Common
{
    public class CurrentDateAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dateTime = Convert.ToDateTime(value);
            return dateTime <= DateTime.Now;
        }
    }
}

3. Decorate DateOfBirth property with our custom CurrentDateAttribute as shown below.

[CurrentDate]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
    get;
    set;
}

Please note that the validation error message can be customized using the named parameter “ErrorMessage” as shown below.

[CurrentDate(ErrorMessage = "Hire Date must be less than or equal to Today's Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
    get;
    set;
}

In the next article, I will discuss Datatype and Compare Attribute in ASP.NET MVC.

SUMMARY

In this article, I try to explain the Creating Custom Validation Attribute in ASP.NET MVC application step by step with some real-time examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article. 

Leave a Reply

Your email address will not be published. Required fields are marked *