Jakobik
Jakobik

Reputation: 1

Is there a way to make localized Compare attribute in ASP.NET MVC?

I'm trying to create a localized website by logged user but don't know how to get LocalizedCompareAttribute working.

I have 2 properties:

[Required]
[LocalizedStringLength(100, "StringLengthErrorMessage", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[DataType(DataType.Password)]
[Display(Name = "ConfirmPassword")]
//[Compare("Password", ErrorMessage = "Passwords do not match.")]
[LocalizedCompare("Password", "ConfirmPasswordErrorMessage")] //Doesn't work
public string ConfirmPassword { get; set; }

and a LocalizedStringLengthAttribute that works fine:

public class LocalizedStringLengthAttribute : StringLengthAttribute
{
    public string ErrorMessageKey { get; set; }

    public LocalizedStringLengthAttribute(int maximumLength, string errorMessageKey)
        : base(maximumLength)
    {
        ErrorMessageKey = errorMessageKey;
    }

    public override string FormatErrorMessage(string name)
    {
        var httpContextAccessor = new HttpContextAccessor();
        var localizer = httpContextAccessor.HttpContext?.RequestServices.GetService<IStringLocalizer<Language>>();

        var localizedMessage = localizer?[ErrorMessageKey] ?? ErrorMessageString;
        return string.Format(localizedMessage, name, MaximumLength, MinimumLength);
    }
}

I created LocalizedCompareAtribute, but couldn't find how to make it work - after adding breakpoint / trying to write to console, function never gets triggered.

public class LocalizedCompareAttribute : ValidationAttribute
{
    private readonly string _otherProperty;
    private readonly string _errorMessageKey;

    public LocalizedCompareAttribute(string otherProperty, string errorMessageKey)
    {
        _otherProperty = otherProperty;
        _errorMessageKey = errorMessageKey;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Get the other property value
        var otherPropertyInfo = validationContext.ObjectType.GetProperty(_otherProperty);

        if (otherPropertyInfo == null)
        {
            return new ValidationResult($"Unknown property: {_otherProperty}");
        }

        var otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance);

        // Compare values
        if (!object.Equals(value, otherValue))
        {
            return new ValidationResult(httpContextAccessor.HttpContext?.RequestServices.GetService<IStringLocalizer<Language>>()?["_errorMessageKey"] ?? "Passwords do not match.");
        }

        return ValidationResult.Success;
    }
}

Any help is appreciated

Upvotes: 0

Views: 65

Answers (0)

Related Questions