ASP.NET MVC 3 Unobtrusive Validation - Before Validating an Event?

Using the unobtrusive ASP.NET MVC3 validation function, how can I run some JavaScript before starting validation? Jquery dispatches a handler after validation for obvious reasons. I can connect to the submit button, but that doesn't seem very elegant. Any suggestions?

EDIT

It seems that my above statement is incorrect. As indicated below, the submit handler starts before validation. Unfortunately, this does not solve my problem.

My revised question:

I need to manipulate the form value after submitting the form, but before jQuery validation. If I changed the value after sending using jQuery submit handler, then jQuery checks the original value, not the new value.

+4
source share
2 answers

The send handler does not start after verification. He works before. Try:

$('form').submit(function () { alert('validation hasn\'t run yet at this point => see there is no red color over your form input fields yet'); if ($(this).valid()) { alert('the form is valid'); } else { alert('the form is not valid'); } }); 

UPDATE:

After a revised question, I still cannot reproduce the problem. Here is my model:

 public class MyModel { [Required] public string Name { get; set; } } 

and here is my opinion:

 @model MyModel <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> @using (Html.BeginForm(null, null, FormMethod.Post, new { })) { @Html.EditorFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name) <input type="submit" value="OK" /> } <script type="text/javascript"> $('form').submit(function () { $('#Name').val('some value'); }); </script> 

Now, if I leave the "Name" field empty and submit the form, the new value will be correctly assigned and the form will be successfully submitted to the server without any errors. If I delete the line $('#Name').val('some value'); which assigns a new value, and try sending the form to empty client-side validation triggers on the client side and the form will not be submitted.

+8
source

I'm not sure if this will be the solution, but you can take a look at the IClientValidatable http://msdn.microsoft.com/en-us/library/system.web.mvc.iclientvalidatable(v=vs.98).aspx interface

Here's an example (pretty old), but should work in the current version: ASP.NET MVC: adding client-side validation to ValidatePasswordLengthAttribute in ASP.NET MVC 3 Preview http://blogs.msdn.com/b/stuartleeks/archive/2010 /07/28/asp-net-mvc-adding-client-side-validation-to-validatepasswordlengthattribute-in-asp-net-mvc-3-preview-1.aspx

0
source

All Articles