ASP.NET MVC 3 Unobtrusive Validation - Before Vali

2019-04-10 01:07发布

问题:

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.

回答1:

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.



回答2:

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