ASP.NET MVC 2 and ComponentModel.DataAnnotations Validation: minimum value attribute
Asked Answered
G

2

5

I'm decorated a ViewModel in my ASP.NET MVC 2 site with System.ComponentModel.DataAnnotations validation attributes. For one of my fields, named Price, I want to validate that the value is not below some extent, in this case 0.

I know that RangeAttribute exists for validation with a lower and an upper extent, but does something like a MinimumValueAttribute exist for validation with only a lower extent?

If not, I guess I'll just roll my own.

Gael answered 4/7, 2010 at 22:44 Comment(5)
remember that rolling your own is easy for server side, but you have to rewrite the validation for client side.Neapolitan
@rockinthesixstring that was why I asked the question rather than just going ahead and implementing my own. of course, you can use Reflector to see how RangeAttribute is doing client-side validation. :)Gael
yup... I just felt it needed to be said for the next guy that comes along to this question. Rolling your own validation is a pain in the ass, especially if you have to reuse the validation on multiple views.Neapolitan
what would be nice is if "somehow" the MVC framework could read through the serverside validation and build custom validators for the client. I suppose another option would be to crack open the source in the HTML Helper Class of MVC and add your custom client side validation in there as well as in the MicrosoftMvcValidation.js, and then recompile it specifically for your app.Neapolitan
you can always use server side validation via an ajax call. Bypass the need to duplicate all the code & craft on both sides.Necklace
D
10

before you roll your own - try [Range(0.05, Double.MaxValue)]

Doge answered 5/7, 2010 at 6:11 Comment(1)
That actually may be the cleanest solution. Will implement it for now, unless someone digs up something even cleaner.Gael
N
2

Not sure if RegularExpression is the "best" solution, but you can give it a shot

"^\$?\d+(\.(\d{2}))?$"
Neapolitan answered 4/7, 2010 at 22:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.