Link to home
Start Free TrialLog in
Avatar of hariaspind
hariaspind

asked on

Comparing two dates.Ensure Enddate is greater then start date.

Dose any one know how to write a custom validation with data annotation using ValidationAttribute .
Avatar of Mrunal
Mrunal
Flag of India image

try this:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"

ErrorMessage="CompareValidator" Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>

and set CompareValidator1.ValueToCompare on page load as:

CompareValidator1.ValueToCompare = Convert.ToDateTime(TextBox2.Text);
Avatar of hariaspind
hariaspind

ASKER

I know this .I am working with Asp.net MVC2.0 .So iam looking to create a custom validation class using ValidationAttribute .
Will this work? Might require some modification, untested
public class DateEqualityAttribute : ValidationAttribute
    {
        public DateEqualityAttribute(DateTime startDate, DateTime endDate)
            : base()
        {
            StartDate = startDate;
            EndDate = endDate;
        }

        public override bool IsValid(object value)
        {
            if (value != null)
            {
                return StartDate < EndDate;
            }
            return true;
        }

        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }
I had the similar thought.Would you please let me know how to use this DateEqualityAttribute.Because my ViewModel has two properties  as below

 public class FundTypeEditViewModel : ViewModelBase
    {
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }
so how to call the DateEqualityAttribute in my ViewModel
ASKER CERTIFIED SOLUTION
Avatar of nullcory
nullcory
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks