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
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.
validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.
You can disable the unobtrusive validation from within the razor code via this Html Helper property: HtmlHelper. ClientValidationEnabled = false; That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.
Unobtrusive JavaScript is a general term that conveys a general set of guidelines or margins to the term REST. REST is nothing but the Representational State Transfer. We can explain Unobtrusive JavaScript as- it is not your particular JavaScript code that you generally use in your markup page.
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(); };
I found this question while looking for a way to set the invalidHandler
, as opposed to the submitHandler
. Interestingly, you can't set invalidHandler
in the same way when using unobtrusive validation.
The function is not fired when an invalid form is detected:
$("form").data("validator").settings.invalidHandler = function (form, validator) { alert('invalid!'); };
This approach works:
$("form").bind("invalid-form.validate", function () { alert('invalid!'); });
It seems to be due to the way that the jquery.validate.unobtrusive.js script initialises the Validate plugin, and the way that the plugin invokes the handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With