Hector Marcia
Hector Marcia

Reputation: 103

C# Custom Validation Attributes: Comparing two Dates in the same model

I created a Custom Validation class that inherits form ValidationAttibute Class. It ensures past dates cannot be selected. Now I have a second date that needs to be at least 3 days after first date. What's the best approach to compare both dates and proceed only if second Date 3 days later than first date (Termination Date and Archiving Date)

This is the code I have for the first date

public class CustomTerminationDate : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime dateTime = Convert.ToDateTime(value);
        return dateTime >= DateTime.Now.Date;
    }
}

It gets implemented as follow:

[Required, Display(Name = "Termination Date")]
    [DataType(DataType.Date)]
    [CustomTerminationDate(ErrorMessage = "Termination Date can not be in the past")]        
    public DateTime TerminationDate { get; set; }

Upvotes: 1

Views: 2320

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11120

Validation attributes are great for validating a single property. I wouldn't attempt to validate multiple properties with attributes, since you can't be certain in what order the fields will be assigned and when the validation should occur.

Instead I would implement IValidatableObject;

public class YourClass: IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (TerminationDate < OtherDate + TimeSpan.FromDays(3))
            yield return new ValidationResult("... error message here ...");
    }
}

Upvotes: 2

Related Questions