views:

112

answers:

3

I'm new to MVC and have a question regarding validation. Is there a way to dynamically set the Error Message?

For example, how could I achieve the following (ignore the hardcoded 50, this could come from the Web.config or specific to the current logged).

[MetadataType(typeof(DocumentValidation))]
public partial class Document
{
    public class DocumentValidation
    {
        private const int MaxLength = 50;

        [Required(ErrorMessage = "Document Title is required")]
        [StringLength(MaxLength, ErrorMessage = "Must be under " + MaxLength.ToString() + " characters")]
        public string Title { get; set; }
    }

}

Thanks,

A: 

Depending how dynamically you're trying to change ErrorMessage. This might be one solution to your problem: haacked.com - Localizing ASP.NET MVC Validation

It's a good guide to get localized error message from the resources.´

Tx3
Well I'm trying to set the StringLength ErrorMessage to be a variable string rather than a constant string. The above example doesn't compile with the error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.I simply want to be able to give custom error messages depending on the circumstance.
DaveHogan
+1  A: 

Check out IDataErrorInfo and this question I asked about IDataErrorInfo vs. DataAnnotations.

Martin
Thanks you've certainly pointed me in the right direction. I did try awarding the bounty but it's saying I have to wait 23hours.
DaveHogan
+1  A: 

This should be possible with dynamic attributes but involves some trickery:

Dynamic Attributes in C#

Developer Art