Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Forked from ardacetinkaya/IValidator.cs
Created June 24, 2020 16:41
Show Gist options
  • Save NDiiong/33ffa015d64cee3018c02df030a7ea2e to your computer and use it in GitHub Desktop.
Save NDiiong/33ffa015d64cee3018c02df030a7ea2e to your computer and use it in GitHub Desktop.
An easy Validation pattern implementation for any kind of application...
//Generic interface for Validators
public interface IValidator<T>
{
IEnumerable<ValidationResult> Validate(T businessEntity);
}
//A simple example to implement validation rules.
//I just wrote two seperate validators to clear out the pattern.
//One validator or more validator can be implemented according to requirment.
public class UserManagement
{
IValidator<User> _userValidator;
IValidator<User> _ageValidator;
public UserManagement()
{
//TODO apply some dependency injection and IoC
_userValidator = new UserNameValidator();
_ageValidator = new UserAgeValidator();
}
public void SaveUser(User entity)
{
IEnumerable<ValidationResult> validationResults = _userValidator.Validate(entity);
if (validationResults > 0)
throw new SomeKindOfException(validationResults);
//TODO do your business
}
public void CanAccess(User entity)
{
IEnumerable<ValidationResult> validationResults = _ageValidator.Validate(entity);
if (validationResults > 0)
throw new SomeKindOfException(validationResults);
}
}
//Just a simple state transfer object for validation
//This can be enhanced with additional properties
public class ValidationResult
{
public string Message { get; private set; }
public ValidationResult(string message)
{
Message = message;
}
}
public class UserAgeValidator : IValidator<User>
{
public IEnumerable<ValidationResult> Validate(User businessEntity)
{
if (businessEntity == null)
yield return new ValidationResult("Entity can not be null");
if(businessEntity.Age<18)
yield return new ValidationResult(String.Format("User's age {0}, is invalid",businessEntity.Age.ToString()));
}
}
//Another example for username check
public class UserNameValidator : IValidator<User>
{
public IEnumerable<ValidationResult> Validate(User businessEntity)
{
if (businessEntity == null)
yield return new ValidationResult("Entity can not be null");
//Let's assume that we have a data repository to check username
if (UserDataRepository.IsUserExists(businessEntity.UserName))
yield return new ValidationResult("There is already a user with same username");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment