Skip to content

Instantly share code, notes, and snippets.

@scionwest
Last active February 4, 2018 00:51
Show Gist options
  • Save scionwest/f279e5e2d4ac4f3870f4b8abdc39642a to your computer and use it in GitHub Desktop.
Save scionwest/f279e5e2d4ac4f3870f4b8abdc39642a to your computer and use it in GitHub Desktop.
Validation 2.0
public class AccountValidator : Validator<Account>
{
public AccountValidator()
{
base.AddSpecifications(
new EmailAddressFormatIsValidSpec(),
new PasswordIsRequiredSpec(),
new StringIsNotEmpty<User>(model => model.Username),
new StringIsNotEmpty<Account>(model => model.AccountNumber),
new UsernameIsRequiredSpec());
}
}
/// <summary>
/// Specification to ensure a string property on a model has a value
/// </summary>
public class StringHasAtLeast8Characters<TEntity> : ISpecification<TEntity>
{
// Store the property selector
private readonly Func<TEntity, string> propertySelector;
// Require the validator to pass in a property selector.
public StringHasAtLeast8Characters(Func<TEntity, string> propertySelector)
{
this.propertySelector = propertySelector;
}
public string ErrorMessage { get; private set; }
public bool IsSatisfiedBy(TEntity entity)
{
// Invoke the delegate so we can get the value from the property specified by the validator.
string propertyValue = this.propertySelector(entity);
// Validate
return propertyValue.Length >= 8;
}
}
public class StringIsNotEmpty<TEntity> : ISpecification<TEntity>
{
// Store the property selector
private readonly Func<TEntity, string> propertySelector;
// Require the validator to pass in a property selector.
public StringIsNotEmpty(Func<TEntity, string> propertySelector)
{
this.propertySelector = propertySelector;
}
public string ErrorMessage { get; private set; }
public bool IsSatisfiedBy(TEntity entity)
{
// Invoke the delegate so we can get the value from the property specified by the validator.
string propertyValue = this.propertySelector(entity);
// Validate
return !string.IsNullOrEmpty(propertyValue);
}
}
public class UserValidator : Validator<User>
{
public UserValidator()
{
base.AddSpecifications(
new EmailAddressFormatIsValidSpec(),
new PasswordIsRequiredSpec(),
new StringHasAtLeast8Characters<User>(model => model.Password),
new StringIsNotEmpty<User>(model => model.Username),
new UsernameIsRequiredSpec());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment