0

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,

3 Answers 3

1
+50

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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

Dynamic Attributes in C#

Comments

0

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.´

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.