Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC form validation without form submission

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>&nbsp;@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.

like image 694
iGanja Avatar asked May 12 '13 01:05

iGanja


2 Answers

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>
like image 71
Guanxi Avatar answered Sep 23 '22 07:09

Guanxi


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.

like image 34
Stefan Avatar answered Sep 21 '22 07:09

Stefan