简体   繁体   中英

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.

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; }

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM