Lets say I have a StartDate and an EndDate and I wnt to check if the EndDate is not more then 3 months apart from the Start Date
public class DateCompare : V
Entity:
[MetadataType(typeof(MyEntity_Validation))]
public partial class MyEntity
{
}
public class MyEntity_Validation
{
[Required(ErrorMessage="'Date from' is required")]
public DateTime DateFrom { get; set; }
[CompareDatesValidatorAttribute("DateFrom")]
public DateTime DateTo { get; set; }
}
Attribute:
public sealed class CompareDatesValidatorAttribute : ValidationAttribute
{
private string _dateToCompare;
private const string _errorMessage = "'{0}' must be greater or equal'{1}'";
public CompareDatesValidatorAttribute(string dateToCompare)
: base(_errorMessage)
{
_dateToCompare = dateToCompare;
}
public override string FormatErrorMessage(string name)
{
return string.Format(_errorMessage, name, _dateToCompare);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dateToCompare = validationContext.ObjectType.GetProperty(_dateToCompare);
var dateToCompareValue = dateToCompare.GetValue(validationContext.ObjectInstance, null);
if (dateToCompareValue != null && value != null && (DateTime)value < (DateTime)dateToCompareValue)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
2. Password
Entity:
public string Password { get; set; }
[Compare("Password", ErrorMessage = "ConfirmPassword must match Password")]
public string ConfirmPassword { get; set; }
I hope it helps