shanky
shanky

Reputation: 386

StringLength not working as expected in MVC4.0

I have a @Html.EditorFor control in MVC 4, for string length validation I have used [StringLength(10)] attribute on the top of the model property initializing, the above control. What it does is whenever a user enters more then 10 chars it gives a message mentioning it can't be more than the defined limit.

But, it does not prohibit user to enter more than the defined limit. Can it be done using DataAnnotations in MVC?

NOTE: I don't want to use any onKeypress event over here.

Upvotes: 2

Views: 1552

Answers (3)

user1331438
user1331438

Reputation: 43

You can give @maxlength=10 to you editorfor e.g.

    @Html.EditorFor(model => model.str, new {  @maxlength=10 })

this way you can restrict users form inserting more than 10 characters.

I hope this will help you.

Upvotes: 1

KevinZhang
KevinZhang

Reputation: 61

You need to write the validate code @Html.ValidationMessageFor in related View(Like edit.cshtml):

        <div class="editor-field">
          @Html.EditorFor(model => model.str)
          @Html.ValidationMessageFor(model => model.str)
        </div>

Thus, it will automatically look for you validation attributes and display some error message in your view page. You can check this post: Adding validation to the model

Upvotes: 0

technophebe
technophebe

Reputation: 494

Seems to be that using a TextBoxfor instead is the easiest way:

@Html.TextBoxFor(model => model.MyField, new {maxlength = 10})

As per this question.

Upvotes: 1

Related Questions