简体   繁体   中英

ASP.NET MVC 3 Unobtrusive Validation - Before Validate Event?

Using ASP.NET MVC3's unobtrusive validation feature how can I run some JavaScript before validation runs? Jquery's submit handler runs after validation for obvious reasons. I can hook into a click on the submit button but that doesn't seem very elegant. Any suggestions?

EDIT

It appears my above statement is incorrect. As was pointed out below the submit handler does run before validation. Unfortunately that does not solve my problem.

My revised question:

I need to manipulate a form value after form submission but before jQuery validation. If I change the value after submission using jQuery's submit handler then jQuery validates the original value not the new value.

The submit handler doesn't run after validation. It runs before. Try it:

$('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 the revised question I am still unable to reproduce the issue. Here's my model:

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

and here's my view:

@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 blank and submit the form, the new value is being properly assigned and the form is successfully submitted to the server without any errors. If I remove the $('#Name').val('some value'); line that assigns a new value and try to submit the form with an empty field client side validation triggers and the form is not submitted.

I'm not sure if it will be a solution but you could have a look to IClientValidatable Interface http://msdn.microsoft.com/en-us/library/system.web.mvc.iclientvalidatable(v=vs.98).aspx

Here's example (quite old) but should work in the current release: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM