ASP.NET MVC Data Annotation Attribute Range specified from another property value

Hi, I have the following in my model MVC Asp.net

TestModel.cs

public class TestModel { public double OpeningAmount { get; set; } [Required(ErrorMessage="Required")] [Display(Name = "amount")] [Range(0 , double.MaxValue, ErrorMessage = "The value must be greater than 0")] public string amount { get; set; } } 

Now from my controller, "OpeningAmount" is assigned.

Finally, when I submit the form, I want to check that the "amount" should be greater than the "OpeningAmonut". so you want to dynamically set the range as

 [Range(minimum = OpeningAmount , double.MaxValue, ErrorMessage = "The value must be greater than 0")] 

I do not want to use only jQuery or javascript, because it will only check on the client side so that I can set the Range attribute at least dynamically than this would be great.

+7
c # asp.net-mvc data-annotations
source share
2 answers

There is no built-in attribute that can handle the dependency between properties.

So, if you want to work with attributes, you will have to write custom.

Se here for an example of what you need.

You can also watch dataannotationsextensions.org

Another solution would be to work with a validation library, e.g. (very nice) FluentValidation .

+1
source share

A stunning nuget has recently appeared that does just that: dynamic annotations are called ExpressiveAnnotations

It allows you to do what was impossible, for example

 [AssertThat("ReturnDate >= Today()")] public DateTime? ReturnDate { get; set; } 

or even

 public bool GoAbroad { get; set; } [RequiredIf("GoAbroad == true")] public string PassportNumber { get; set; } 
+8
source share

All Articles