views:

936

answers:

1

Lets say I have a StartDate and an EndDate and I wnt to check if the EndDate is not more then 3 months apart from the Start Date

public class DateCompare : ValidationAttribute 
 {
    public String StartDate { get; set; }
    public String EndDate { get; set; }

    //Constructor to take in the property names that are supposed to be checked
    public DateCompare(String startDate, String endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }

    public override bool IsValid(object value)
    {
        var str = value.ToString();
        if (string.IsNullOrEmpty(str))
            return true;

        DateTime theEndDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        DateTime theStartDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(3);
        return (DateTime.Compare(theStartDate, theEndDate) > 0);
    }
}

and I would like to implement this into my validation

[DateCompare("StartDate", "EndDate", ErrorMessage = "The Deal can only be 3 months long!")]

I know I get an error here... but how can I do this sort of business rule validation in asp.net mvc

+2  A: 

I have only figured out how to do this at the class level but not the at property level. If you create an MVC application, the Account model shows the approach illustrated below.

Class:

  [PropertiesMustMatch("Password",
            "ConfirmPassword", ErrorMessage =
            "Password and confirmation password
            do not match.")]
                public class RegisterModel
                {

                    [Required(ErrorMessage = "Required")]
                    [DataType(DataType.EmailAddress)]
                    [DisplayName("Your Email")]
                    public string Email { get; set; }              

                    [Required(ErrorMessage = "Required")]
                    [ValidatePasswordLength]
                    [DataType(DataType.Password)]
                    [DisplayName("Password")]
                    public string Password { get; set; }

                    [Required(ErrorMessage = "Required")]
                    [DataType(DataType.Password)]
                    [DisplayName("Re-enter password")]
                    public string ConfirmPassword { get; set; }                
                }

Validation Method:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class PropertiesMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";

        private readonly object _typeId = new object();

        public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
            ConfirmProperty = confirmProperty;
        }

        public string ConfirmProperty
        {
            get;
            private set;
        }

        public string OriginalProperty
        {
            get;
            private set;
        }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                OriginalProperty, ConfirmProperty);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
        }
}
scottrakes
Did you create that class? Or did you find it somewhere? When the passwords don't match it's not displaying the error. I must be missing something.Uhh nevermind, it comes with MVC
Chuck Conway
It is part of the base MVC application. It is adding the error to _form, not to a specific entity.
scottrakes