Fluent Validation extension method


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.