dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.97k stars 4.66k forks source link

Add MinValueAttribute and MaxValueAttribute for Model Validation - [MinValue()] [MaxValue()] #40408

Open vsfeedback opened 4 years ago

vsfeedback commented 4 years ago

This issue has been moved from a ticket on Developer Community.


Let's say we have a model with a string property Name. You can define attributes like MinLength or MaxLength (which are part of System.ComponentModel.DataAnnotations).

[MaxLength(40)]
[MinLength(4)]
public string Name { get; set; }

Now we add an int property Age and want to specify a min value of 21. At the moment you would have to use the RangeAttribute like the following examples show (or create your own attribute class), because there is no way to define a minimum or maximum value.

[Range(21, Int32.MaxValue)]
public int Age { get; set; }

or if we want to say the max value is 40

[Range(0, 40)]
public int Age { get; set; }

There might also be cases where you don't want to allow the int value 0. Then you would write that like

[Range(1, Int32.MaxValue)]
public int Age { get; set; }

We always have to define a range and have to specify additional information. Sometimes you don't want to specify the other range part or you don't know it.

It would be easier to read and write and more similar to string validation, if there would be the attributes MinValue and MaxValue, so you can define the 3 previous examples like this:

[MinValue(21)]
public int Age { get; set; }
[MaxValue(40)]
public int Age { get; set; }
[MinValue(1)]
public int Age { get; set; }
--- ### Original Comments #### Feedback Bot on 6/15/2020, 02:51 AM: Thank you for taking the time to provide your suggestion.  We will do some preliminary checks to make sure we can proceed further.  We'll provide an update once the issue has been triaged by the product team.
ghost commented 4 years ago

Tagging subscribers to this area: @ajcvickers See info in area-owners.md if you want to be subscribed.

vmonatko commented 2 years ago

Like this idea because possible to add different ErrorMessage when the value is greater than or less than limits.

yigdo commented 1 year ago

This idea would simplify the process a lot. I like it.

gabrielgfaria commented 2 months ago

I'm interested in this one, can I start working on it?