.net 使用数据注解进行验证不起作用

r3i60tvu  于 2022-11-26  发布在  .NET
关注(0)|答案(2)|浏览(215)

我正在开发一个带有客户购买模型的REST API。我已经应用了一些验证,但是我发现对十进制类型的属性的验证不起作用,而对类型为字符串的属性的验证成功。
我的行为是,如果不添加属性(例如total),则不应用验证,并且此属性采用十进制类型的默认值,即0.0
也就是说,我有以下模型:

public class CustomerPurchase : BaseEntity
    {
        [Required(ErrorMessage = "PurchaseFolioRequired")]
        public string Folio { get; set; }

        [Required(ErrorMessage = "PurchaseIvaRequired")]
[Range(typeof(Decimal), "0", "1000000000000000000", ErrorMessage = "PurchaseInvalidVat")]
        public decimal Iva { get; set; }

        [Required(ErrorMessage = "PurchaseSubtotalRequired")]
[Range(typeof(Decimal), "0", "1000000000000000000", ErrorMessage = "PurchaseInvalidSubtotal")]
        public decimal Subtotal { get; set; }

        [Required(ErrorMessage = "PurchaseTotalRequired")]
[Range(typeof(Decimal), "0", "1000000000000000000", ErrorMessage = "PurchaseInvalidTotal")]
        public decimal Total { get; set; }

        [Required(ErrorMessage = "PurchaseTotalLettersRequired")]
        public string TotalLetters { get; set; }

        [Required(ErrorMessage = "PurchaseEmployeeRequired")]
        [BsonRepresentation(BsonType.ObjectId)]
        public string UserId { get; set; }

        [Required(ErrorMessage = "PurchaseProductRequired")]
        [MinLength(1, ErrorMessage = "PurchaseProductRequired")]
        public ProductSold[] Products { get; set; }

        [Required(ErrorMessage = "PurchasePaymentRequired")]
        [MinLength(1, ErrorMessage = "PurchasePaymentRequired")]
        public Payment[] Payments { get; set; }

        [Required(ErrorMessage = "PurchaseClientRequired")]
        public Client Client { get; set; }
    }

这个应用程序是错误的?,或者有一个方法来严格应用这个验证。
感谢阅读

k97glaaz

k97glaaz1#

decimal是一个value type,所以它总是有一个默认值-0,所以它总是通过你的验证。

public class CustomerPurchase : BaseEntity
{
    ....
    [Required(ErrorMessage = "PurchaseIvaRequired")]
    [Range(typeof(Decimal), "0", "1000000000000000000", ErrorMessage = "PurchaseInvalidVat")]
    public decimal? Iva { get; set; }
    ...
}

RequiredAttribute的文档对此也非常清楚:
RequiredAttribute属性指定在验证表单上的字段时,该字段必须包含值。如果属性为null、包含空字符串(“”)或仅包含空白字符,则会引发验证异常。

UPD

在C# 11中添加了required关键字后,您可以尝试使用它来修复此问题:

public class CustomerPurchase : BaseEntity
{
    ....
    public required decimal Iva { get; set; }
    ...
}
nwlqm0z1

nwlqm0z12#

您可以编写如下代码:

[Range(1, 100)]
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }

发件人:Part 8, add validation to an ASP.NET Core Razor Page

相关问题