Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 365
Dilip0165 Avatar asked Jan 09 '14 13:01

Dilip0165


2 Answers

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; }
like image 97
Korayem Avatar answered Nov 09 '22 02:11

Korayem


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 .

like image 32
Raphaël Althaus Avatar answered Nov 09 '22 03:11

Raphaël Althaus