Validation with data annotations does not work

Viewed 125

I'm develop a REST API with a customer purchase model. I have applied some validations, but I seen that validations on the properties with decimal type does not work, however, tha validatios on the properties with type string work successfull.

The behavior I have is if not add the property, for example, total, tha validation does not applied and this property take the default value for decimal types, that is 0.0

That is, I have the following model:

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; }
    }

This application is wrong?, or there is a way to applied strictly this validation.

Thanks for reading

2 Answers

decimal is a value type, so it always has a default value - 0 in this case, so it always passes your validation. So you can just make them nullable:

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

Docs for RequiredAttribute are also pretty clear about it:

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.

Related