-
-
Save emiaj/2928059 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 | |
{ | |
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); | |
} | |
} | |
} |
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 | |
{ | |
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 | |
} | |
} |
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