using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace EnVisage.Models.ValidationAttributes.NonProjectTime { public class NPTimeEffectiveDateRequiredAttribute : ValidationAttributeBase, IClientValidatable { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && !string.IsNullOrWhiteSpace(value.ToString())) return ValidationResult.Success; var propertyId = validationContext.ObjectType.GetProperty("Id"); var propertyPermanent = validationContext.ObjectType.GetProperty("Permanent"); var propertyPermanentOld = validationContext.ObjectType.GetProperty("PermanentOld"); if (propertyId != null && propertyPermanent != null && propertyPermanentOld != 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); // if user edits permanent np time the effective date is required var isValid = !(id != Guid.Empty && permanent && permanentOld); if (isValid) return ValidationResult.Success; } return new ValidationResult(ErrorMessage); } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "nptimeeffectivedaterequired" }; var id = ((Guid?)GetPropertyValue("Id", metadata, context) ?? Guid.Empty); var permanentOld = ((bool?)GetPropertyValue("PermanentOld", metadata, context) ?? false); rule.ValidationParameters["id"] = id.ToString(); rule.ValidationParameters["permanentold"] = Convert.ToInt32(permanentOld); rule.ValidationParameters["permanent"] = "Permanent"; yield return rule; } } }