gpt4 book ai didi

c# - 使用数据注释进行验证不起作用

转载 作者:行者123 更新时间:2023-12-03 23:03:22 24 4
gpt4 key购买 nike

我正在开发一个带有客户购买模型的 REST API。我已经应用了一些验证,但我看到对十进制类型的属性的验证不起作用,但是,对字符串类型的属性的验证成功工作。
我的行为是如果不添加属性,例如,总计,不应用验证,并且此属性采用十进制类型的默认值,即 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; }
}
这个应用程序是错误的?,或者有一种方法可以严格应用这个验证。
谢谢阅读

最佳答案

decimalvalue type ,所以它总是有一个默认值 - 0在这种情况下,它总是通过您的验证。所以你可以制作它们 nullable :

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

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

关于c# - 使用数据注释进行验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64187540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com