Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have these two fields in my model:

[Required(ErrorMessage="The start date is required")]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime startDate { get; set; }

[Required(ErrorMessage="The end date is required")]
[Display(Name="End Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime endDate{ get; set; }

I require that endDate must be greater than startDate. I tried using [Compare("startDate")] but this only works for the equal operation.

What should I use for the "greater than" operation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
944 views
Welcome To Ask or Share your Answers For Others

1 Answer

Take a look at Fluent Validation or MVC Foolproof Validation: those can help you a lot.

With Foolproof for example there is a [GreaterThan("StartDate")] annotation than you can use on your date property.

Or if you don't want to use other libraries, you can implement your own custom validation by implementing IValidatableObject on your model:

public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]    
    public DateTime EndDate { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           yield return new ValidationResult(
               errorMessage: "EndDate must be greater than StartDate",
               memberNames: new[] { "EndDate" }
          );
       }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...