Validation ErrorMessage value

本文关键字:value ErrorMessage Validation | 更新日期: 2023-09-27 18:10:33

如何为这样的实体发出自定义验证器错误消息?:

收据超过发票金额15000

我的财产

[InvoiceAmountNotExeeded(ErrorMessage = "Receipts exeeded invoice amount  of {0}")]
public int Amount {get; set; }
在验证器

:

var errorMsg = FormatErrorMessage(string.Format(validationContext.DisplayName,invoice.Amount))

问题是我正在收到:收据超过发票金额。注意它是如何写属性名而不是属性值的。建议吗?

EDIT: Code added

public class InvoiceAmountNotExeededAttribute : ValidationAttribute {
        public InvoiceAmountNotExeededAttribute()
        {            
        } 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var factId = ....;
            var db = new Entities();
            var fact = db.Invoices.Find(factId);
            var amountRecibos = ...;
            var amount = Convert.ToInt32(value);
            if (amountRecibos + amount > fact.Amount ){
                var errorMsg = FormatErrorMessage(string.Format(validationContext.DisplayName,invoice.Amount));
                return new ValidationResult(errorMsg);
            }            
            return ValidationResult.Success;
        }
    }

Validation ErrorMessage value

出现这种行为的原因是您引用了validationContext。DisplayName默认设置为属性名称(在您的情况下为"Amount")。所以对你来说,string.Format(validationContext.DisplayName,invoice.Amount)只返回"Amount"。而不是这个,尝试应用这个:

var errorMsg = FormatErrorMessage(invoice.Amount.ToString());
return new ValidationResult(errorMsg);

这样,你将传递给FormatErroMessage不是DisplayName的属性,而是Amount的值,FormatErrorMessage将使用它的模式从ErrorMessage属性属性。这应该是你想要的