Alex Rivera | Logout

Either ErrorMessageString or ErrorMessageResourceName must be set, but not both error using CreditCardAttribute

Asked 2012-09-18T10:12:21.763
53

This is my model:

namespace MvcApplication2.Models
{
    public class CreditCard
    {
        [CreditCard(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "CardNumberInvalid")]
        public string CardNumber { get; set; }
    }
}

This is my Messages.resx:

Name Value

CardNumberInvalid Check your card number is correct

And this is my view:

@model MvcApplication2.Models.CreditCard
@Html.TextBoxFor(m => m.CardNumber);

In MVC version 3 this works without error. In MVC 4 when I go to this page I get an excpetion saying "Either ErrorMessageString or ErrorMessageResourceName must be set, but not both". This is only happening with the CreditCardAttribute. Other validation attributes such as RequiredAttribute work fine. I have only set the ErrorMessageResourceName. I have not set the ErrorMessageString, so do not understand what I have done wrong. Can anyone help please?

Edit
Report

1 Answer

10

I had this problem because I had implemented a RequiredAttributeAdapter, which was setting the ErrorMessageResourceName property automatically.

You can fix it by checking to see if the ErrorMessage property has been set before setting the ErrorMessageResourceName:

/// <summary>
/// Creates a new instance of the RequiredAttributeAdapter, used for switching the default required message
/// format
/// </summary>
public CustomMessageRequiredAttributeAdapter(
    ModelMetadata metadata,
    ControllerContext context,
    RequiredAttribute attribute
)
    : base(metadata, context, attribute)
{
    if (string.IsNullOrEmpty(attribute.ErrorMessage))
    {
        attribute.ErrorMessageResourceType = typeof (ValidationMessages);
        attribute.ErrorMessageResourceName = "PropertyValueRequired";
    }
}
answered 2013-04-25T09:44:41.660

Your Answer