How to specify a min but no max decimal using the

2020-05-16 13:21发布

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 correct way to do this is.

[Range(typeof(decimal), "0", "??"] public decimal Price { get; set; }

10条回答
一夜七次
2楼-- · 2020-05-16 13:45

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-05-16 13:47

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.

查看更多
劳资没心,怎么记你
4楼-- · 2020-05-16 13:48

You can use:

[Min(0)]

This will impose a required minimum value of 0 (zero), and no maximum value.

You need DataAnnotationsExtensions to use this.

查看更多
老娘就宠你
5楼-- · 2020-05-16 13:55

How about something like this:

[Range(0.0, Double.MaxValue)]

That should do what you are looking for and you can avoid using strings.

查看更多
一夜七次
6楼-- · 2020-05-16 13:55

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.")]
查看更多
放荡不羁爱自由
7楼-- · 2020-05-16 13:56

It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }
查看更多
登录 后发表回答