Guest User

Untitled

a guest
Oct 17th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. public class Validator<T>
  2. {
  3. private readonly IEnumerable<ValidationRule<T>> _rules;
  4.  
  5. public Validator(IEnumerable<ValidationRule<T>> rules)
  6. {
  7. _rules = rules;
  8. }
  9.  
  10. public static ValidatorBuilder<T> Builder => new ValidatorBuilder<T>();
  11.  
  12. public bool IsValid(T obj)
  13. {
  14. return _rules.All(x => x.IsMet(obj));
  15. }
  16.  
  17. public IEnumerable<Validation> Validate(T obj)
  18. {
  19. if (obj == null)
  20. {
  21. yield return new Validation(false, $"Object of type {typeof(T).Name} does not meet the requirement: ({typeof(T).Name} != null)");
  22. yield break;
  23. }
  24.  
  25. foreach (var rule in _rules)
  26. {
  27. var isValid = rule.IsMet(obj);
  28. yield return new Validation(
  29. isValid,
  30. isValid
  31. ? $"Object of type {typeof(T).Name} meets the requirement: {rule}"
  32. : $"Object of type {typeof(T).Name} does not meet the requirement: {rule}");
  33. }
  34. }
  35. }
  36.  
  37. public class ValidatorBuilder<T>
  38. {
  39. private readonly List<ValidationRule<T>> _rules = new List<ValidationRule<T>>();
  40.  
  41. public ValidatorBuilder<T> Where(Expression<Func<T, bool>> expression)
  42. {
  43. var expressionString = expression.ToString();
  44.  
  45. var variableName = Regex.Match(expressionString, "^([a-z0-9_]+) => ").Groups[1].Value;
  46. expressionString = Regex.Replace(expressionString, "^[a-z0-9_]+ => ", string.Empty);
  47. expressionString = Regex.Replace(expressionString, $"{variableName}\.", $"{typeof(T).Name}.");
  48.  
  49. _rules.Add(new ValidationRule<T>(expressionString, expression.Compile()));
  50. return this;
  51. }
  52.  
  53. public Validator<T> Build()
  54. {
  55. return new Validator<T>(_rules);
  56. }
  57. }
  58.  
  59. public class Validation
  60. {
  61. public Validation(bool success, string message)
  62. {
  63. Success = success;
  64. Message = message;
  65. }
  66. public bool Success { get; }
  67. public string Message { get; }
  68. }
  69.  
  70. var builder = Validator<Person>.Builder;
  71.  
  72. var personValidator =
  73. builder
  74. .Where(p => !string.IsNullOrEmpty(p.FirstName))
  75. .Where(p => p.LastName != null)
  76. .Where(p => !p.LastName.StartsWith("D"))
  77. .Build();
  78.  
  79. personValidator.Validate(new Person
  80. {
  81. FirstName = "John",
  82. LastName = "Doe"
  83. })
  84. .Dump();
Add Comment
Please, Sign In to add comment