Jaqen H'ghar
Jaqen H'ghar

Reputation: 1879

Textbox validation in MVC2

I have added Required attribute to one of my properties of Model class as follows -

[Required(ErrorMessage="UserID should not be blank")]
[DisplayName("User Name")]
public string UserName { get; set; }

Inside my view, which inherits the class containing above property, I have tried to apply validaton to a textbox as follows -

 <%= Html.TextBoxFor(model => Model.UserName, new { @class = "login-input",       @name="UserName" })%>
 <%= Html.ValidationMessageFor(model => Model.UserName)%>

But when I run this app, and invokes the post(using a button click), without entering anything in the textbox; I don't get the text box validated?

Can anyone please tell me what may be the reason that is prohibiting the textbox validation?

Thanks in advance, kaps

Upvotes: 1

Views: 1899

Answers (6)

Rashmi Pandit
Rashmi Pandit

Reputation: 23808

This will work only if the HttpPost Action method takes the class (which contains the property UserName) as one of its input parameters.

So if your code is something like this:

public class User
{
  public User() { } // Make sure the class has an empty constructor

  [Required(AllowEmptyStrings = false, ErrorMessage="UserID should not be blank")] 
  [DisplayName("User Name")] 
  public string UserName { get; set; } 
}

Then the following action method will validate UserName:

[HttpPost]
public ActionResult AddUser(User user)
{ 
  ...
}

If your action method is something like this, it will NOT consider your validation attributes:

[HttpPost]
public ActionResult AddUser(string userName)
{ 
  ...
}

Also, model => Model.UserName or model => model.UserName does not make a difference.

Upvotes: 1

swapneel
swapneel

Reputation: 3061

dont forget to include MicrosoftMvcValidation.js MicrosoftAjax.js into your master page .

And as mentioned by Rashmi's logic - use model binding to make validation work.

[HttpPost] public ActionResult AddUser(User user) {
... }

Upvotes: 1

Jaqen H&#39;ghar
Jaqen H&#39;ghar

Reputation: 1879

I failed to mention that the post method is receiving formcollection as parameter. I replaced that with the class containing the property. The problem gets solved. Apologies.

Upvotes: 0

mxmissile
mxmissile

Reputation: 11673

Required does not mean what you think it does. Read the update.

Upvotes: 0

David Glenn
David Glenn

Reputation: 24522

Try removing the '@name="UserName"' from your Html.TextBoxFor

Upvotes: 0

ali62b
ali62b

Reputation: 5403

change model => Model.UserName to model => model.UserName

Upvotes: 1

Related Questions