castle-validators

Castle Validators how to Validate Is Lesser/Greater Than Or Equal


I see the ValidateIsLesser and ValidateIsGreater attributes. But what if I want to do a ValidateIsLesserOrEqual and/or ValidateIsGreaterOrEqual. Do I just need to write these custom attributes or is there pre-built capabilities for this that I am having a hard time finding?

[ValidateNonEmpty]
[ValidateDate]
[ValidateIsLesser(IsLesserValidationType.Date, "EndDate", "Start Date must be before End Date.")]
public DateTime StartDate { get; set; }

[ValidateNonEmpty]
[ValidateDate]
[ValidateIsGreater(IsGreaterValidationType.Date, "StartDate", "End Date must be after the Start Date.")]
public DateTime EndDate { get; set; }

Solution

  • You can use the ValidateSelf attribute and supply your own validation for the OrEqual comparisons:

    [ValidateNonEmpty]
    [ValidateDate]
    public DateTime StartDate { get; set; }
    
    [ValidateNonEmpty]
    [ValidateDate]
    public DateTime EndDate { get; set; }
    
    [ValidateSelf]
    public void ValidateDate(ErrorSummary errors)
    {
        if (StartDate >= EndDate)
            errors.RegisterErrorMessage("StartDate", "Start date must be earlier than end date.");
    }