using EnVisage.Code; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace EnVisage.Models.ValidationAttributes.NonProjectTime { public class NPTimeEffectiveDateAttribute : ValidationAttributeBase, IClientValidatable { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) return ValidationResult.Success; var propertyId = validationContext.ObjectType.GetProperty("Id"); var propertyPermanent = validationContext.ObjectType.GetProperty("Permanent"); var propertyPermanentOld = validationContext.ObjectType.GetProperty("PermanentOld"); var propertyStartDate = validationContext.ObjectType.GetProperty("NonProjectTimeStartDate"); var propertyStartDateOld = validationContext.ObjectType.GetProperty("NonProjectTimeStartDateOld"); if (propertyId != null && propertyPermanent != null && propertyPermanentOld != null && propertyStartDate != null && propertyStartDateOld != null) { var id = ((Guid?)propertyId.GetValue(validationContext.ObjectInstance) ?? Guid.Empty); var permanentOld = ((bool?)propertyPermanentOld.GetValue(validationContext.ObjectInstance) ?? false); var permanent = ((bool?)propertyPermanent.GetValue(validationContext.ObjectInstance) ?? false); var startDateOld = ((DateTime?)propertyStartDateOld.GetValue(validationContext.ObjectInstance) ?? DateTime.MinValue); var startDate = ((DateTime?)propertyStartDate.GetValue(validationContext.ObjectInstance) ?? DateTime.MinValue); var effectiveDate = ((DateTime?)value ?? DateTime.MinValue); // if user edits permanent np time the effective date is required var isValid = !(id != Guid.Empty && permanent && permanentOld && startDateOld > startDate && effectiveDate != startDate); if (isValid) return ValidationResult.Success; } return new ValidationResult(ErrorMessage); } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "nptimeeffectivedate" }; var id = ((Guid?)GetPropertyValue("Id", metadata, context) ?? Guid.Empty); var permanentOld = ((bool?)GetPropertyValue("PermanentOld", metadata, context) ?? false); var startDateOld = ((DateTime?)GetPropertyValue("NonProjectTimeStartDateOld", metadata, context)); rule.ValidationParameters["id"] = id.ToString(); rule.ValidationParameters["permanentold"] = Convert.ToInt32(permanentOld); rule.ValidationParameters["permanent"] = "Permanent"; rule.ValidationParameters["startdateold"] = startDateOld.HasValue ? Utils.ConvertToUnixDate(startDateOld.Value) : 0; rule.ValidationParameters["startdate"] = "NonProjectTimeStartDate"; yield return rule; } } }