Fluent验证扩展方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fluent验证扩展方法相关的知识,希望对你有一定的参考价值。

  1. public class GreaterThanNullableDate<T> : PropertyValidator
  2. {
  3. private Expression<Func<T, DateTime?>> mTarget;
  4. public GreaterThanNullableDate(Expression<Func<T, DateTime?>> expression)
  5. : base("Property {PropertyName} greater than another date!")
  6. {
  7.  
  8. mTarget = expression;
  9. }
  10.  
  11. protected override bool IsValid(PropertyValidatorContext context)
  12. {
  13. Func<T, DateTime?> oFunc = mTarget.Compile();
  14. //Type oType = mTarget.Parameters[0].Type;
  15. DateTime? oTargetDateTime = oFunc.Invoke((T)context.Instance);
  16.  
  17. DateTime? oSource = context.PropertyValue as DateTime?;
  18.  
  19. if (oSource != null && oTargetDateTime != null)
  20. {
  21. if (oSource < oTargetDateTime)
  22. return false;
  23. }
  24.  
  25. return true;
  26. }
  27. }
  28. public static class DefaultValidatorExtensions
  29. {
  30. 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)
  31. {
  32.  
  33. return ruleBuilder.SetValidator(new GreaterThanNullableDate<T>(expression));
  34. }
  35. }
  36.  
  37. public partial class NIBRSMasterValidator : AbstractValidator<NIBRSMaster>
  38. {//only good for NIBRSoffense which means only basic data, nothing about selected code objects.
  39. public NIBRSMasterValidator()
  40. {
  41. RuleFor(p => p.IncidentDateTime).Must(NotBeFutureDate).WithMessage("NIBRS incident date time: No future date allowed.");
  42. RuleFor(p => p.IncidentDateTime).GreaterThanNullableDate(p => p.ExceptionalClearanceDateTime).WithMessage("NIBRS incident date cannot be earlier than exceptional clearance date.");
  43.  
  44. }
  45. private bool NotBeFutureDate(DateTime? pValue)
  46. {//where can i move this to? to share. AbstractValidator?
  47.  
  48. if (pValue > DateTime.Now)
  49. return false;
  50.  
  51. return true;
  52. }
  53.  
  54. }

以上是关于Fluent验证扩展方法的主要内容,如果未能解决你的问题,请参考以下文章

封装jQuery Validate扩展验证方法

jQuery Validate 提交表单验证失败扩展方法

jquery表单数据验证扩展方法

Easyui的validatebox验证方法自定义扩展

验证范围中日期时间的扩展方法

使用Fluent Validator验证Bool