Revision: 42073
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at February 26, 2011 08:48 by marktaichen
Initial Code
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)
{
return ruleBuilder.SetValidator(new GreaterThanNullableDate<T>(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;
}
}
Initial URL
Initial Description
Initial Title
Fluent Validation extension method
Initial Tags
validation, extension
Initial Language
C#