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

hariaspind
hariaspind used Ask the Experts™
on
Dose any one know how to write a custom validation with data annotation using ValidationAttribute .
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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);

Author

Commented:
I know this .I am working with Asp.net MVC2.0 .So iam looking to create a custom validation class using ValidationAttribute .

Commented:
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; }
    }
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Author

Commented:
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
Commented:
I've actually never done this before but after some quick googling I think this will work:
public class DateEqualityAttribute : ValidationAttribute
    {
        public DateEqualityAttribute(DateTime startDate)
            : base()
        {
            StartDate = startDate;
        }

        public override bool IsValid(object value)
        {
            if (value != null)
            {

                return StartDate < Convert.ToDateTime(value);
            }
            return true;
        }

        public DateTime StartDate { get; set; }
    }

public class FundTypeEditViewModel : ViewModelBase
    {
        public DateTime StartDate { get; set; }
        [DateEquality(StartDate)]
        public DateTime EndDate { get; set; }
    }

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial