3

I need a text box which should be exactly of 7 characters, for which I have written

Html.TextboxFor(x=>x.Number, new {maxLength = "7"};

This case takes me only 7 characters , but if I want to take less than 7, it is taking? Is there any property like maxlength which takes 7 charecters only.

regards, michael velayadu

michael
  • 575
  • 2
  • 14
  • 27

4 Answers4

2

For what its worth, none of these answers are very clear. What you are trying to do is set a minimum and maximum length attribute essentially. There are basically a few ways you can accomplish this using data annotations.

The easiest way:

[MinLength(7)]
[MaxLength(7)]

Using StringLengthAttribute... StringLength has two overloaded methods. Both have the int parameter @maximumLength and one of the overloads includes NamedParameters. So for maxlength you wouldn't use a named parameter but for minlength you would:

[StringLength(7, MinimumLength=7)]

If you want to be really confusing you could also do it this way:

[MinLength(7)]
[StringLength(7)]
sanpaco
  • 785
  • 1
  • 14
  • 32
2

There is no Html attribute on a textbox for Minimum Length. You can use data annotations to enforce a maximum and minimum text length for that field...

This is a pretty good walkthrough on using data annotations: Stephen Walther on ASP.Net

jlnorsworthy
  • 3,914
  • 28
  • 34
  • Dataannotations work for postback, moreover the annotation StringLength(7) enables for less than 7 also .i want to know if there is any attribute for minlength also, but as "jlnorswothy" said there isn't , i should go for custon control. – michael Mar 24 '11 at 08:16
0

You do not need to create a custom validator for this. You can use the StringLength attribute to achieve what you want out of the box:

[StringLength(MinimumLength=7, MaximumLength=7)]
public int Number { get; set; }
Ant P
  • 24,820
  • 5
  • 68
  • 105
0

With DataAnnotations using regular expressions you can enforce a string of exactly 7 charachters. DataAnnotations can also be used client-side, you just have to enable it.

Check this post for more info: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx