Loading

ASP.NET MVC

How to create Custom Validation Attribute in MVC?. The Complete ASP.NET MVC Developer Course 2023 [Videos].

In this article, I am going to discuss how to Create Custom Validation Attribute in ASP.NET MVC Application. Please read the Range Attribute in the ASP.NET MVC article before proceeding to this article as I am going to use the same example. 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, lets say, we want the end date to be todays 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 your application, you will get the error saying – An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

To fix this error, 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 the 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())
{
}
}
}

Finally, decorate the â€œDateOfBirth” property with our custom DateRangeAttribute as shown below. Notice that, we are only passing the minimum date value. The maximum date value will be todays 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;
}
Another example of creating a custom validation attribute in ASP.NET MVC. 

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

  1. Right-click on the “Common” folder and add a class file with the 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;
}
}
}

Decorate the â€œ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 Todays Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth
{
get;
set;
}

See All

Comments (301 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /301

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /301

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /301