Skip to content

Instantly share code, notes, and snippets.

@emiaj
Forked from jmarnold/UniqueUsernameRule.cs
Created June 14, 2012 04:59
Show Gist options
  • Save emiaj/2928059 to your computer and use it in GitHub Desktop.
Save emiaj/2928059 to your computer and use it in GitHub Desktop.
DI-Enabled validation rules
public class UniqueUsernameRule : IFieldValidationRule
{
public void Validate(Accessor accessor, ValidationContext context)
{
var email = accessor.GetValue(context.Target) as EmailAddress;
var repository = context.Services.Get<IEntityRepository>();
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
{
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();
}
}
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