I'm unable to get custom validators to work on the client side. In the ASP.NET MVC5 I used to use Simple Injector to register validatiors:
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
container.Register<IValidatorFactory, ApplicationValidatorFactory>(Lifestyle.Singleton);
container.Register(typeof(IValidator<>), assemblies);
container.RegisterConditional(typeof(IValidator<>),
typeof(ValidateNothingDecorator<>),
Lifestyle.Singleton,
context => !context.Handled);
and register all custom validators:
// Register Simple Injector validation factory in FV
FluentValidationModelValidatorProvider.Configure(provider =>
{
provider.ValidatorFactory = new ApplicationValidatorFactory(container);
provider.AddImplicitRequiredValidator = false;
provider.Add(typeof(UniqueEmailValidator),
(m, c, d, v) => new UniqueEmailPropertyValidator(m, c, d, v));
provider.Add(typeof(UniqueUsernameValidator),
(m, c, d, v) => new UniqueUsernamePropertyValidator(m, c, d, v));
provider.Add(typeof(StringNoSpacesValidator),
(m, c, d, v) => new StringNoSpacesPropertyValidator(m, c, d, v));
provider.Add(typeof(PasswordStrengthValidator),
(m, c, d, v) => new PasswordStrengthPropertyValidator(m, c, d, v));
});
Add these methods on the JS side:
jQuery.validator.addMethod("nospaces", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, language.username_has_spaces);
jQuery.validator.unobtrusive.adapters.add("nospaces", function (options) {
options.rules["nospaces"] = true;
if (options.message) {
options.messages["nospaces"] = options.message;
}
});
jQuery.validator.unobtrusive.adapters.add("passwordmeter", function (options) {
options.rules["passwordmeter"] = true;
if (options.message) {
options.messages["passwordmeter"] = options.message;
}
});
and that's it! It worked flawlessly!
How do I do the same with ASP.NET Core 1.1?
I have followed documentation which mentions to register it using Microsoft's DI:
services.AddMvc().AddFluentValidation(
fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
But that has several problems:
- can't get custom validators to work on the client (built-in ones work great)
- services used inside custom validators that are already registered with SimpleInjector have to be registered again one by one using Microsoft's DI.
services.AddTransient<IUserRegistrationService, UserRegistrationService>();