html.textboxfor() should be exactly 7 characters
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
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
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)]
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
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; }
精彩评论