Created
February 4, 2018 00:43
-
-
Save scionwest/77a1b55e78f69dffdfda8dc662c287bb to your computer and use it in GitHub Desktop.
Shared Validation
This file contains hidden or 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
/// <summary> | |
/// Specification to ensure a string property on a model has a value | |
/// </summary> | |
public class MinimumLengthSpecification<TEntity> : ISpecification<TEntity> | |
{ | |
// Store the property selector | |
private readonly Func<TEntity, string> propertySelector; | |
private readonly int minimumLength; | |
// Require the validator to pass in a property selector. | |
// Having something pass in the minimum length violates the concept of a "specification" | |
// because now the spec does nothing but do a compare. | |
// The specification doesn't actually act as a spec by specifying what the minimum length is. | |
public MinimumLengthSpecification(Func<TEntity, string> propertySelector, int minimumLength) | |
{ | |
this.propertySelector = propertySelector; | |
this.minimumLength = minimumLength; | |
} | |
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 >= this.minimumLength; | |
} | |
} |
This file contains hidden or 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
public class UserValidation : Validator<User> | |
{ | |
public UserValidation() | |
{ | |
base.AddSpecifications( | |
new EmailAddressFormatIsValidSpec(), | |
new PasswordIsRequiredSpec(), | |
new MinimumLengthSpecification<User>(model => model.Password, minimumLength: 8), | |
new MinimumLengthSpecification<User>(model => model.Username, minimumLength: 6), | |
new UsernameIsRequiredSpec()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment