-
-
Save NDiiong/07978cbf59a3bd8666e26b1c991dddf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var model = new Test() { }; | |
var validator = new Validator<Test>(); | |
var result = new Validator<Test>() | |
.AddRule(t => t.Name, new ValidatorNameRule()) | |
.Validate(model); | |
} | |
} | |
public interface IValidationRule<T> | |
{ | |
ValidationResult Validate(T arg); | |
} | |
public interface IValidator<TInstance> | |
where TInstance : class | |
{ | |
IValidator<TInstance> AddRule<TProp>( | |
Expression<Func<TInstance, TProp>> expression, | |
IValidationRule<TProp> validationRule); | |
ValidationResult Validate(TInstance instance); | |
} | |
public class ValidationResult | |
{ | |
public IEnumerable<ValidationError> ValidationErrors { get; set; } | |
= new List<ValidationError>(); | |
public bool Valid { get; set; } = true; | |
public ValidationResult Merge (ValidationResult validationResult) | |
{ | |
return new ValidationResult() | |
{ | |
ValidationErrors = this.ValidationErrors.Concat(validationResult.ValidationErrors), | |
Valid = this.Valid && validationResult.Valid | |
}; | |
} | |
} | |
public class ValidationError | |
{ | |
public string Message { get; set; } | |
public int HttpStatusCode { get; set; } | |
} | |
public class Validator<TInstance> : IValidator<TInstance> | |
where TInstance : class | |
{ | |
private class ValidatorEntry<TProp> | |
{ | |
public Expression<Func<TInstance, TProp>> Expression { get; set; } | |
public IValidationRule<TProp> ValidatorRule { get; set; } | |
} | |
IList<dynamic> _container = new List<dynamic>(); | |
public IValidator<TInstance> AddRule<TProp>( | |
Expression<Func<TInstance, TProp>> expression, | |
IValidationRule<TProp> validationRule | |
) | |
{ | |
var validationEntry = new ValidatorEntry<TProp>() | |
{ | |
Expression = expression, | |
ValidatorRule = validationRule | |
}; | |
_container.Add(validationEntry); | |
return this; | |
} | |
public ValidationResult Validate(TInstance instance) | |
{ | |
var validationResult = new ValidationResult(); | |
foreach (var validationEntry in _container) | |
{ | |
var value = validationEntry.Expression.Compile() | |
.Invoke(instance); | |
validationResult = validationResult | |
.Merge(validationEntry.ValidatorRule | |
.Validate(value)); | |
} | |
return validationResult; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment