I have a standard form populated by an MVC model with standard [Required] validation. I want to "submit" this form data via AJAX, not by a submit, and I would like to take advantage of the built-in MVC/razor validation features. I can't figure out how to fire the client-side validation without triggering the form submit event.
Here is my razor markup:
@using (Html.BeginForm()) {
<span class="label">Team Name:</span> @Html.TextBoxFor(m => m.Name})
@Html.ValidationMessageFor(m => m.Name)
And here is my model:
public class Team
{
[Required(ErrorMessage = "Required")]
public string Name { get; set; }
It seems like this should be an easy thing to do. It works beautifully on submit. I just need to know how to invoke the validation method manually.
This feature is enabled by default, but it has not been working because you might not have added links to the required JavaScript libraries.
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Since this is the top answer, when you google for "mvc validation form submit" I have to add another point, which coast me a few hours. When you are using
@Html.ValidationSummary()
in your code, the form get's submited, even if you added these libraries and set
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
in the appSettings property of your webconfig.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With