Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 466
Mark Avatar asked Jan 19 '23 11:01

Mark


1 Answers

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.

like image 80
Darin Dimitrov Avatar answered Jan 26 '23 02:01

Darin Dimitrov