10

I am using DataAnnotations in an ASP.NET MVC 1 application to check for Required fields and numerical ranges using the Required and Range attributes.

I am looking for the best way to validate the length of strings in a few input text boxes. I see that there is a RegularExpression attribute that could do the job but I was wondering if there was a more specific attribute to do this?

Also if anyone can point me to a decent resource regarding using DataAnnotations I would be very grateful.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Andy Rose
  • 16,770
  • 7
  • 43
  • 49

1 Answers1

9

How about the StringLength attribute?

Anders Fjeldstad
  • 10,724
  • 2
  • 33
  • 50
  • @Anders - [StringLength] isn't specific to MVC, right? The documentation doesn't suggest so, but I'm using it in a straight console app and it isn't firing on a rule violation. All examples I Google reference MVC. – Howiecamp Mar 26 '12 at 16:17
  • @Howiecamp The attribute in itself is "just a class" and can be used wherever you like. It's up to the application to actually do anything with it though. ASP.NET MVC looks for the data annotation attributes by default; if you want to use them in another context that hasn't got this built in you will have to add the functionality yourself. I think you could apply [this solution](http://stackoverflow.com/a/3783328/121146) to your problem. – Anders Fjeldstad Mar 28 '12 at 07:50