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

前端 未结 8 1960
囚心锁ツ
囚心锁ツ 2020-12-24 04:44

This is my model:

namespace MvcApplication2.Models
{
    public class CreditCard
    {
        [CreditCard(ErrorMessageResourceType = typeof(Messages), Error         


        
8条回答
  •  情深已故
    2020-12-24 05:35

    Since anyone who is using custom validation attributes and also wants to load error messages from resources for localization purposes, would face this problem i share my workaround here.
    assume that you have a custom validation attribute like this one

    [FileTypeMustBe("jpg")]
    public HttpPostedFileBase MyFile {get; set;}
    

    in your custom validation attribute add this code

    public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
              ErrorMessageString, name, ValidFileType);
        }
    

    ValidFileType is name of a property which takes the input argument of custom validation attribute (jpg here),well now we can decorate our model property the way we like it to be

    [FileTypeMustBe("jpg", ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "WrongFileTypeError")]
    public HttpPostedFileBase MyFile {get; set;}
    

    as you see there's no need to add ErrorMessage=null anymore cause we took care of it in custom validation class. just do not forget if you had initialized any error message string in your custom validation , you have to remove it now and use FormatErrorMessage instead.

提交回复
热议问题