Ich habe 2 Eigenschaften:
Code: Select all
[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; }
Code: Select all
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();
var localizedMessage = localizer?[ErrorMessageKey] ?? ErrorMessageString;
return string.Format(localizedMessage, name, MaximumLength, MinimumLength);
}
}
Code: Select all
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()?["_errorMessageKey"] ?? "Passwords do not match.");
}
return ValidationResult.Success;
}
}