Gibt es eine Möglichkeit, lokalisiertes Vergleichsattribut in ASP.NET MVC zu erstellen?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Gibt es eine Möglichkeit, lokalisiertes Vergleichsattribut in ASP.NET MVC zu erstellen?

Post by Anonymous »

Ich versuche, eine lokalisierte Website durch protokollierten Benutzer zu erstellen, weiß aber nicht, wie man localized comareAttribute funktioniert.
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; }
und Lokalisierte StringLengthAttribute Das funktioniert gut:

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);
}
}
Ich habe Localized CompareAtribute erstellt, konnte aber nicht finden, wie es funktioniert - Nach dem Hinzufügen von Haltepunkt/Versuch, an die Konsole zu schreiben, wird die Funktion nie ausgelöst. < Br />

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;
}
}
Jede Hilfe wird geschätzt

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post