简体   繁体   中英

ASP.NET MVC data annotations attribute Range set from another property value

Hi I have following in my Asp.net MVc Model

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 assign .

Finaly when I submit form I want to check that "amount" must be greater than "OpeningAmonut" . so want to set Range dynamically like

[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 check only client side so possible I can set Range attribute minimum dynamically than it would be great for.

Recently there's been an amazing nuget that does just that: dynamic annotations and it's called ExpressiveAnnotations

It allows you to do things that weren't possible before such as

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

or even

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

There's no built-in attribute which can work with dependence between properties.

So if you want to work with attributes, you'll have to write a custom one.

Se here for an example of what you need.

You can also take a look at dataannotationsextensions.org

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM