Fluent验证扩展方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fluent验证扩展方法相关的知识,希望对你有一定的参考价值。
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; } }
以上是关于Fluent验证扩展方法的主要内容,如果未能解决你的问题,请参考以下文章