MVC Custom Data Annotations

Custom Annotation

/CustomValidation/ValidateAgeAttribute.cs

This can be used to apply a custom range validation to the given date time value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace PROJECTNAMESPACE.CustomValidation
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ValidateAgeAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "Your age is invalid, your {0} should fall between {1} and {2}";

public DateTime MinimumDateProperty { get; private set; }
public DateTime MaximumDateProperty { get; private set; }

public ValidateAgeAttribute(
int minimumAgeProperty,
int maximumAgeProperty)
: base(DefaultErrorMessage)
{
MaximumDateProperty = DateTime.Now.AddYears(minimumAgeProperty * -1);
MinimumDateProperty = DateTime.Now.AddYears(maximumAgeProperty * -1);
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
DateTime parsedValue = (DateTime)value;

if (parsedValue <= MinimumDateProperty || parsedValue >= MaximumDateProperty)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;

}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ValidationType = "validateage",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
};

rule.ValidationParameters.Add("minumumdate", MinimumDateProperty.ToShortDateString());
rule.ValidationParameters.Add("maximumdate", MaximumDateProperty.ToShortDateString());

yield return rule;
}

public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, MinimumDateProperty.ToShortDateString(), MaximumDateProperty.ToShortDateString());
}
}
}

Applied to Model

1
2
3
4
5
[Required]
[Display(Name = "Effective From")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[ValidateAge(15, 65)]
public DateTime DateOfBirth { get; set; }

Reference

Unobtrusive Client and Server Side Age Validation in MVC using Custom Data Annotations (http://www.macaalay.com)