RealityDysfunction
RealityDysfunction

Reputation: 2639

Custom Validation Message, language specific

I have a model that looks something like this:

[LocalizedRegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", "RedesignEmailValidationError")]
public string EmailAddress { get; set; }

[Compare("EmailAddress", ErrorMessage = "Emails mismatch!")]
public string EmailConfirm { get; set; }

The problem is that the Error Message is not localized. What would be the best approach to handle this?

PS: I receive the language specific text that needs to be on this form in a model; ideally I would like to use the text provided there.

Upvotes: 0

Views: 242

Answers (2)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22074

Also if you're not relying on default resource provider, you have to implement it yourself.

Like:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
public sealed class LocalizedDisplayNameAttribute : DisplayNameAttribute {
  public LocalizedDisplayNameAttribute() {
  }

  public LocalizedDisplayNameAttribute(object context) {
    Context = context;
  }

  public object Context { get; set; }

  public override string DisplayName {
    get {
      // TODO: override based on CultureInfo.CurrentCulture and Context here 
      return "LocalizedAttributeName";
    }
  }
}

[AttributeUsage(AttributeTargets.Property)]
public class LocalizedCompareAttribute : CompareAttribute {

  public object Context { get; set; }

  public LocalizedCompareAttribute(string otherProperty)
    : base(otherProperty) {
  }

  public override string FormatErrorMessage(string name) {
    // TODO: override based on CultureInfo.CurrentCulture and Context here 
    string format = "Field '{0}' should have the same value as '{1}'.";
    return string.Format(CultureInfo.CurrentCulture, format, name, OtherPropertyDisplayName);      
  }
}

etc.

Usage:

[LocalizedCompare("EmailAddress", Context = "ResourceKey_EmailMismatch")]
[LocalizedDisplayName("ResourceKey_Email")]
public string EmailConfirm { get; set; }

Upvotes: 2

Vladimirs
Vladimirs

Reputation: 8609

You need to use ErrorMessageResourceName and ErrorMessageResourceType

Should be something like that:

[Compare("EmailAddress", ErrorMessageResourceName = "ConfirmEmailErrorMessage", ErrorMessageResourceType=typeof(your_resource_type)]
public string EmailConfirm { get; set; }

Upvotes: 2

Related Questions