1

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; }
2
  • 1
    IMHO cross field validation should be in an IValidatableObject implementation. Commented Jan 10, 2022 at 2:55
  • Jeremy please post it to accept as answer. this resolved the issue. Commented Jan 10, 2022 at 3:46

1 Answer 1

2

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 ...");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.