Created
February 26, 2018 15:39
-
-
Save aleor/bc191b84917d8bb527abe8681573e39f to your computer and use it in GitHub Desktop.
asp net mvc custom validation attribute (checks if age is in allowed range based on date of birth)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
namespace SampleProject.Validators | |
{ | |
public class AgeRangeAttribute : ValidationAttribute | |
{ | |
private readonly int _minAge; | |
private readonly int _maxAge; | |
public AgeRangeAttribute(int minAge, int maxAge) | |
{ | |
_minAge = minAge; | |
_maxAge = maxAge; | |
ErrorMessage = "{0} must be between {1} and {2}"; | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
if (!(value is DateTime)) | |
{ | |
throw new ValidationException("AgeRange is only valid for DateTime properties."); | |
} | |
var birthdate = (DateTime)value; | |
var today = DateTime.Today; | |
var age = today.Year - birthdate.Year; | |
if (birthdate > today.AddYears(-age)) { age--; } | |
if (age < _minAge || age > _maxAge) | |
{ | |
return new ValidationResult(this.FormatErrorMessage(validationContext.MemberName)); | |
} | |
return ValidationResult.Success; | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return string.Format(this.ErrorMessageString, name, _minAge, _maxAge); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment