Reputation: 1105
I have a simple ASP.NET MVC form, everything work fine, the only thing is I want to automatically show the validation message when I selects a field. But to show the message validation I need to send the form. Do I need to use ajax ? thanks for your help.
Here is my form :
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "TestForm" }))
{
<div>
@Html.LabelFor(m => m.FirstName)
</div>
<div>
@Html.TextBoxFor(m => m.FirstName, new { id = "FirstName" })
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div>
@Html.LabelFor(m => m.LastName)
</div>
<div>
@Html.TextBoxFor(m => m.LastName, new { id = "LastName" })
@Html.ValidationMessageFor(m => m.LastName)
</div>
...
}
Model
public class TestModel
{
[Required(ErrorMessage = "FirstName should blabla")]
[StringLength(4, ErrorMessage = "You must...", MinimumLength = 1)]
[DataType(DataType.Text)]
[Display(Name = "FirstName")]
public string FirstName { get; set; }
[Required(ErrorMessage = "LastName should blabla")]
[StringLength(4, ErrorMessage = "You must...", MinimumLength = 1)]
[DataType(DataType.Text)]
[Display(Name = "LastName")]
public string LastName { get; set; }
...
}
Upvotes: 1
Views: 121
Reputation: 4736
Yes, you need to take steps to enable client-side validation. This blog post talks about using the built-in validators. You'll need @{ Html.EnableClientValidation(); }
before the Html.BeginForm
call, or you can do it in the Web.config.
This VS Magazine article discusses the process of registering a JavaScript function and a server-side method to answer the JavaScript request. Though it was written for MVC 3, it should apply equally well to MVC 4.
Upvotes: 1