Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Created June 14, 2012 04:32
Show Gist options
  • Save jmarnold/2928011 to your computer and use it in GitHub Desktop.
Save jmarnold/2928011 to your computer and use it in GitHub Desktop.
DI-Enabled validation rules
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);
}
}
}
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
}
}
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