How to Replace Standard DataAnnotations Error Messages

I am using System.ComponontModel.DataAnnotations to validate model objects. How can I replace the standard message attributes (Required and StringLength) without providing an ErrorMessage attribute for each of them or a subclass that classifies them?

+7
data-annotations
source share
2 answers

Writing a new post because I need more formatting than comments.

See ValidationAttribute , the base class of validation attributes.

If a validation error occurs, an error message will be generated by the method:

public virtual string FormatErrorMessage(string name) { return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, new object[] { name }); } 

Next, view the ErrorMessageString property:

 protected string ErrorMessageString { get { if (this._resourceModeAccessorIncomplete) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.ValidationAttribute_NeedBothResourceTypeAndResourceName, new object[0])); } return this.ResourceAccessor(); } } 

The ResourceAccessor property can be set from:

 ValidationAttribute..ctor(Func<String>) ValidationAttribute.set_ErrorMessage(String) : Void ValidationAttribute.SetResourceAccessorByPropertyLookup() : Void 

Firstly, it is used by dervided fonts to format messages, secondly, the case when we install the ErrorMessage error message , and thirdly, when using resource strings. Depending on your situation, you can use ErrorMessageResourceName .

Elsewhere, consider derivative constructors, for our example: Range attribute:

 private RangeAttribute() : base((Func<string>) (() => DataAnnotationsResources.RangeAttribute_ValidationError)) { } 

Here RangeAttribute_ValidationError is loaded from the resource:

 internal static string RangeAttribute_ValidationError { get { return ResourceManager.GetString("RangeAttribute_ValidationError", resourceCulture); } } 

So, you can create a resource file for different default tan settings and overwrite messages there:

http://www.codeproject.com/KB/aspnet/SatelliteAssemblies.aspx

http://msdn.microsoft.com/en-us/library/aa645513(VS.71).aspx

+8
source share

You can use the ErrorMessage property of the ValidationAttribute base class for all DataAnnotations validators.

For example:

 [Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}")] public int id; 

Perhaps this will help.

+6
source share

All Articles