/ Published in: C#
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public class GreaterThanNullableDate<T> : PropertyValidator { private Expression<Func<T, DateTime?>> mTarget; public GreaterThanNullableDate(Expression<Func<T, DateTime?>> expression) : base("Property {PropertyName} greater than another date!") { mTarget = expression; } protected override bool IsValid(PropertyValidatorContext context) { Func<T, DateTime?> oFunc = mTarget.Compile(); //Type oType = mTarget.Parameters[0].Type; DateTime? oTargetDateTime = oFunc.Invoke((T)context.Instance); DateTime? oSource = context.PropertyValue as DateTime?; if (oSource != null && oTargetDateTime != null) { if (oSource < oTargetDateTime) return false; } return true; } } public static class DefaultValidatorExtensions { public static IRuleBuilderOptions<T, DateTime?> GreaterThanNullableDate<T>(this IRuleBuilder<T, DateTime?> ruleBuilder, Expression<Func<T, DateTime?>> expression) //Expression<PropertySelector<T, DateTime?>> expression)//Expression<Func<T, DateTime?>> expression) { } } public partial class NIBRSMasterValidator : AbstractValidator<NIBRSMaster> {//only good for NIBRSoffense which means only basic data, nothing about selected code objects. public NIBRSMasterValidator() { RuleFor(p => p.IncidentDateTime).Must(NotBeFutureDate).WithMessage("NIBRS incident date time: No future date allowed."); RuleFor(p => p.IncidentDateTime).GreaterThanNullableDate(p => p.ExceptionalClearanceDateTime).WithMessage("NIBRS incident date cannot be earlier than exceptional clearance date."); } private bool NotBeFutureDate(DateTime? pValue) {//where can i move this to? to share. AbstractValidator? if (pValue > DateTime.Now) return false; return true; } }