I'm creating a Post Russia shipping plugin and must validate the customer's delivery address. I did not find an easy way to include my validation without changing source. I’ve seen few questions about address validation in the forum, but there are not suitable answers.
As a result, I had to change the source:
1. Added notification publisher in NopValidatorFactory^
var instance = EngineContext.Current.ResolveUnregistered(validatorAttribute.ValidatorType);
if (instance != null)
{
try
{
var eventPublisher = EngineContext.Current.Resolve<IEventPublisher>();
eventPublisher.ValidatorPrepare(type, instance);
}
catch
{
// ignored
}
}
2. In the plugin implemented IConsumer<ValidatorPreparedEvent> and its handler:
public void HandleEvent(ValidatorPreparedEvent eventMessage)
{
var isAddressModel = eventMessage.ModelType.FullName == Nop.Web.Models.Common.AddressModel";
if (!isAddressModel)
return;
var typeInfo = eventMessage.Validator.GetType().GetTypeInfo();
var methodInfo = typeInfo.GetMethod("AddRule");
if (methodInfo != null)
{
var rule = new object[] {new AddressValidationRule()};
methodInfo.Invoke(eventMessage.Validator, rule);
}
}
I use invoke because I don't want to create refference from plugin to Nop.Web - AddressModel is there.
This method does work. Could the team add something similar in the official code please? Changing the code is bad practics.
Thank you in advance,
Serge