Created
June 14, 2012 04:32
-
-
Save jmarnold/2928011 to your computer and use it in GitHub Desktop.
DI-Enabled validation rules
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
public class UniqueUsernameRule : IFieldValidationRule | |
{ | |
private readonly IEntityRepository _repository; | |
public UniqueUsernameRule(IEntityRepository repository) | |
{ | |
_repository = repository; | |
} | |
public void Validate(Accessor accessor, ValidationContext context) | |
{ | |
var email = accessor.GetValue(context.Target) as EmailAddress; | |
if (email == null) return; | |
var isUnique = !_repository.All<User>().Any(x => x.Username.Equals(email.Address, StringComparison.OrdinalIgnoreCase)); | |
if(!isUnique) | |
{ | |
context.Notification.RegisterMessage(accessor, SurgeryLogisticsValidationKeys.USERNAME_IN_USE); | |
} | |
} | |
} |
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
public class UniqueUsernameRuleSource : IFieldValidationSource | |
{ | |
private readonly IEntityRepository _repository; | |
public UniqueUsernameRuleSource(IEntityRepository repository) | |
{ | |
_repository = repository; | |
} | |
public IEnumerable<IFieldValidationRule> RulesFor(PropertyInfo property) | |
{ | |
var accessor = ReflectionHelper.GetAccessor<RegistrationRequest>(x => x.Email); | |
var prop = new SingleProperty(property); | |
if(accessor.Equals(prop)) | |
{ | |
yield return new UniqueUsernameRule(_repository); | |
} | |
} | |
public void Validate() | |
{ | |
// no-op | |
} | |
} |
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
public class ValidationStructureMapRegistry : Registry | |
{ | |
public ValidationStructureMapRegistry() | |
{ | |
this.FubuValidation(); | |
// ... | |
For<IFieldValidationSource>().Add<UniqueUsernameRuleSource>(); | |
// Or just do an assembly scan and add all of your sources | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment