Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Validator<T>
- {
- private readonly IEnumerable<ValidationRule<T>> _rules;
- public Validator(IEnumerable<ValidationRule<T>> rules)
- {
- _rules = rules;
- }
- public static ValidatorBuilder<T> Builder => new ValidatorBuilder<T>();
- public bool IsValid(T obj)
- {
- return _rules.All(x => x.IsMet(obj));
- }
- public IEnumerable<Validation> Validate(T obj)
- {
- if (obj == null)
- {
- yield return new Validation(false, $"Object of type {typeof(T).Name} does not meet the requirement: ({typeof(T).Name} != null)");
- yield break;
- }
- foreach (var rule in _rules)
- {
- var isValid = rule.IsMet(obj);
- yield return new Validation(
- isValid,
- isValid
- ? $"Object of type {typeof(T).Name} meets the requirement: {rule}"
- : $"Object of type {typeof(T).Name} does not meet the requirement: {rule}");
- }
- }
- }
- public class ValidatorBuilder<T>
- {
- private readonly List<ValidationRule<T>> _rules = new List<ValidationRule<T>>();
- public ValidatorBuilder<T> Where(Expression<Func<T, bool>> expression)
- {
- var expressionString = expression.ToString();
- var variableName = Regex.Match(expressionString, "^([a-z0-9_]+) => ").Groups[1].Value;
- expressionString = Regex.Replace(expressionString, "^[a-z0-9_]+ => ", string.Empty);
- expressionString = Regex.Replace(expressionString, $"{variableName}\.", $"{typeof(T).Name}.");
- _rules.Add(new ValidationRule<T>(expressionString, expression.Compile()));
- return this;
- }
- public Validator<T> Build()
- {
- return new Validator<T>(_rules);
- }
- }
- public class Validation
- {
- public Validation(bool success, string message)
- {
- Success = success;
- Message = message;
- }
- public bool Success { get; }
- public string Message { get; }
- }
- var builder = Validator<Person>.Builder;
- var personValidator =
- builder
- .Where(p => !string.IsNullOrEmpty(p.FirstName))
- .Where(p => p.LastName != null)
- .Where(p => !p.LastName.StartsWith("D"))
- .Build();
- personValidator.Validate(new Person
- {
- FirstName = "John",
- LastName = "Doe"
- })
- .Dump();
Add Comment
Please, Sign In to add comment