How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?

WooWaaBob picture WooWaaBob · Jan 20, 2011 · Viewed 25.8k times · Source

I'm validating a form using the new unobtrusive validation features in ASP.NET MVC 3.

So there is no code that I have written to setup jQuery validate to start validating my form. Its all done by loading the jQuery.validate.unobtrusive.js library.

Unfortunately I need to whack in a 'are you sure?' message box when the form is valid but before submitting. With jQuery validate you would add the option handleSubmit when initialising like so:

$("#my_form").validate({
  rules: {
    field1: "required",
    field1: {email: true },
    field2: "required"
  },
  submitHandler: function(form) {
     if(confirm('Are you sure?')) {
       form.submit();
     }
  }
});

But you don't need to initialise when using the unobtrusive library.

Any ideas where/how I can add a submit handler in that case?

Thx

Answer

petrhaus picture petrhaus · Jan 21, 2011

The unobtrusive library will attach the validator on all forms, so you have to replace the submitHandler this way:

$("form").data("validator").settings.submitHandler = function (form) { alert('submit'); form.submit(); };