Search code examples
asp.net-mvcvalidationasp.net-mvc-2asp.net-mvc-2-validation

ASP.NET MVC 2.0 Validation and ErrorMessages


I need to set the ErrorMessage property of the DataAnnotation's validation attribute in MVC 2.0. For example I should be able to pass an ID instead of the actual error message for the Model property, for example...

[StringLength(2, ErrorMessage = "EmailContentID")] 
[DataType(DataType.EmailAddress)]         
public string Email { get; set; } 

Then use this ID ("EmailContentID") to retrieve some content(error message) from a another service e.g database. Then the error error message is displayed to the user instead of the ID. In order to do this I need to set the DataAnnotation validation attribute’s ErrorMessage property.

It seems like a stright forward task by just overriding the DataAnnotationsModelValidatorProvider‘s protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)

However it is complicated now....

A. MVC DatannotationsModelValidator’s ErrorMessage property is readonly. So I cannot set anything here B. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so I cannot set it again. If I try to set it I get “The property cannot set more than once…” error message.

 public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider 
 { 
      protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata,  ControllerContext context, IEnumerable<Attribute> attributes) 
       { 
            IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes); 

             foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>()) 
             { 
                 messageId = validator.ErrorMessage; 
                 validator.ErrorMessage = "Error string from DB And" + messageId ; 
             } 

            //...... 
       } 
  } 

Can anyone please give me the right direction on this?

Thanks in advance.


Solution

  • I personally wouldnt create a new provider inheriting the original provider but I would create a new Attribute inheriting either the ValidationAttribute or the StringLengthAttribute.

    Something Like this

    public class MyNewValidationAttribute : StringLengthAttribute
    {
        public int ErrorMessageId
        {
            set { 
                    var myErrorMessageFromDB = ""; //query database and get message.
                    this.ErrorMessage = myErrorMessageFromDB;  
                }
        }
    }
    

    Now when you assign the attribute

    [StringLength(2, ErrorMessageId = 1 //equals id from database
    )]