1

I have created one view ,in which i have one text box,i want to put required field validation on that text box.

@Html.TextBox("txtFirst", "", htmlAttributes: new {@maxlength="9"})
3
  • Are you asking for the validation in the Domain object to be incorporated? Commented May 1, 2012 at 19:53
  • This is not how it's being done. you should learn how to use the jQuery validation plugin Commented May 1, 2012 at 19:53
  • so,there is not any kind if thing like required field validator which we have in asp.net...I cannot use model with that becuase this field is not map with any model from my application Commented May 1, 2012 at 19:59

1 Answer 1

3

First I must say the best way to do validation in MVC is to put the Data Annotation attributes above the properties in your model like with this:

[Required]
[StringLength(9)]
public string Foo {get; set;}

// This will force the validation in the client side.
@Html.TextBoxFor(m => m.Foo);

The good thing in this approach(except that it's usually less to write) that it work client-side and Server-side as well.

If you want to do the validation in the view and not in the Model for some reason, you simply need to add the required class to the textbox:

@Html.TextBox("txtFirst", "", htmlAttributes: new {@class = "required", maxlength="9"})
Sign up to request clarification or add additional context in comments.

3 Comments

All this gets is client side validation - client side can still be bypassed and if server side validation isn't in place then there is a data integrity problem
Hy,Above thing solved my issue,but now i want 2 validation for same field.For e.g:@Html.TextBox("txtFirst", "", htmlAttributes: new { @class = "required email", maxlength = "9" }) this field is required and it must be valid email this solved my problem but i am not able to display different validation message,it means if user not enter value then error message is please enter email address and wrong email address then it should display please enter valid email.please keep in mind i don't want to use model for that,i want to use view only.
@jats. Please ask it in a new thread, and I or someone else will be glad to help you with that. you can add a link to this thread if you think it can help the question be clearer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.