How to specify a min but no max decimal using the range data annotation attribute?

后端 未结 10 1716
旧时难觅i
旧时难觅i 2021-01-31 01:02

I would like to specify that a decimal field for a price must be >= 0 but I don\'t really want to impose a max value.

Here\'s what I have so far...I\'m not sure what the

相关标签:
10条回答
  • 2021-01-31 01:31

    using Range with

    [Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
    
    [Range(typeof(Decimal),"0.0", "1000000000000000000"]
    

    Hope it will help

    0 讨论(0)
  • 2021-01-31 01:32

    If you are concerned about the string looking nice you could do this:

        [Range(0, Double.PositiveInfinity)]
    

    This will have a default error message of:

    The field SuchAndSuch must be between 0 and Infinity.

    0 讨论(0)
  • 2021-01-31 01:34

    I was going to try something like this:

    [Range(typeof(decimal), ((double)0).ToString(), ((double)decimal.MaxValue).ToString(), ErrorMessage = "Amount must be greater than or equal to zero.")]
    

    The problem with doing this, though, is that the compiler wants a constant expression, which disallows ((double)0).ToString(). The compiler will take

    [Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")]
    
    0 讨论(0)
  • 2021-01-31 01:37

    If you're working with prices, I'm sure you can safely assume nothing will cost more than 1 trillion dollars.

    I'd use:

    [Range(0.0, 1000000000000)]
    

    Or if you really need it, just paste in the value of Decimal.MaxValue (without the commas): 79,228,162,514,264,337,593,543,950,335

    Either one of these will work well if you're not from Zimbabwe.

    0 讨论(0)
提交回复
热议问题