Base solution for your next web application
Open Closed

Translation in ICustomValidate #1373


User avatar
0
maikeloh created

I am not able to find the correct way to translate the string of the ValidationResult on this DTO with ICustomValidate. This is a simple DTO i have more complex validation rules on others DTO, the question is how translate the message here. Any help? Thanks a lot in advantage.

public class TestDto : EntityDto<long>, IInputDto, ICustomValidate {

    public virtual long IdNumber{ get; set; }

    
    public virtual string Description { get; set; }

    public int TenantId { get; set; }

    public void AddValidationErrors(List&lt;ValidationResult&gt; results)
    {
        if (IdNumber.ToString().Length != 16)
        {
            results.Add(new ValidationResult("The IdNumber must have 16 chars of length"));
        }
    }
}

4 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    The problem here is that you can not access to ILocalizationManager since DTOs can not inject dependencies. But your requirement is pretty reasonable and should be a way.

    Currently, the only way is to use statics (which is not good for unit tests). Use this:

    var localizedText = LocalizationHelper.GetString("MySource", "MyLocalizationKey");
    

    I created an issue related to that: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues/1177">https://github.com/aspnetboilerplate/as ... ssues/1177</a>

  • User Avatar
    0
    hikalkan created
    Support Team

    This is done and will be released in next version: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues/1381">https://github.com/aspnetboilerplate/as ... ssues/1381</a>

  • User Avatar
    0
    zokho created

    How can we use localization in Dto class that implements ICustomValidate?

    public void AddValidationErrors(CustomValidationContext context)
            {
                context.IocResolver.
                if (!AreAllTimesValid(this.TimesOfDay))
                    context.Results.Add(new ValidationResult("TimeOfDayIsNotValid"));
            }
    

    a sample code would be appreciated :)

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can try to do it like this:

    public void AddValidationErrors(CustomValidationContext context)
    {
        var localizationManager = context.IocResolver.Resolve<ILocalizationManager>();
        var localizedValue = localizationManager.GetSource("SourceName").GetString("LocalizationKey");
    }