After I managed to create and display a jQuery dialog using the $().dialog() function, I wanted to replace my ad-hoc validation code with a “real” validation plugin, namely jQuery Validation. (naming consistency of jQuery plugins did not seem to matter until now, as there are several plugins with similar names in this area)![]()
As much as I tried, the validator’s valid() would always return true, and debugging revealed that there were no elements to be checked, even though I had declared them in the validate() method.
Finally I came across this answer on SO, stating
the jQuery-UI dialog does not append to the form, it appends just before
</body>, so the elements to validate are outside the<form></form>section
and suggesting the solution
$("#mydiv")
.dialog("open")
.parent()
.appendTo(jQuery("form:first"));
Now it was obvious what’s happening: the dialog() function moves the <div> outside ASP.Net’s default form element (id=’aspnetForm’), directly under the <body> element.
Since I want to have several jQuery dialogs in my ASP.Net page, and cannot freely add <form> tags in the source code (especially not in .ascx and not in .aspx inside a MasterPage), I decided to create a <form> on the fly, and open the dialog inside the new form:
if (!$("#myForm").length) {
$("<form>")
.attr("id", "myForm")
.attr("name", "myForm")
.appendTo($("body"));
}
var d = $("#myDialog").dialog({
autoOpen: false,
modal: true,
open: function () {
$("#myForm").validate({ ... }).resetForm();
},
buttons: [
{ id: "OK",
click: function() {
if (!$("#myForm").valid())
return false;
... process data ...
$("#myDialog").dialog("close");
}
}
]
});
d.dialog("open")
.parent().appendTo($("#myForm"));
Note that I added the call to resetForm() to clear errors from a previous execution of the dialog.
You can call the form validation using the .valid() method and simply leave the dialog open if a validation error occurred.
Have a look at the demos for help regarding HTML and CSS declarations.
Pingback: Fixing jQuery Validation with changing validators « devioblog
Pingback: Inserting and Updating List Items with ASP.Net MVC and JQuery | devioblog