I'm trying to use errorPlacement with the Validator plugin for jquery, but I'm having issues with the offset. If the element is hidden at the time of validation (in a different tab), the offset returns the value 0,0 (top left corner of screen).
$(document).ready(function() {
var tabs = $("#tabs").tabs();
var validator = $("#myForm").validate({
errorElement: "div",
wrapper: "div", // a wrapper around the error message
errorPlacement: function(error, element) {
if (element.parent().hasClass('group')){
element = element.parent();
}
offset = element.position();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top);
}
});
}
Any suggestions on how to fix this? I would recalculate the offsets when the tab changes or something, but it's being done in validate which I understood is only called once.
Thanks for the help!
Edit:
I still seem to be stuck on this. The problem I'm finding is that (at least from what I read), I can't call validate more than once. Do you think somehow adding each error message and element key pair to a list wo开发者_JAVA百科uld work, or is that a dirty hack? I'm not really sure how to add them to a list anyway. Any suggestions would be much appreciated. Thanks!!
This: "The problem I'm finding is that (at least from what I read), I can't call validate more than once." is actually not true. You can manually trigger form validation any time from your javascript code, and with a little trick you can even specify what part of your form should be validated.
Assuming that:
- you have a tabbed form,
- tabs are wrapped in divs
- hidden tabs have css class "inactive", visible tab has css class "active"
- you have forward and back button on your form for navigation along the tabs
I'd do something like this:
$(document).ready(function() {
var validator = $("#myForm").validate({
... // your settings
ignore : ['#tabs .inactive input'] // tells the validator to only validate elements on your current tab
});
}
$(".forward").click(function() {
if (validator.form()) { // triggers validation of the currently visible form inputs
// step forward to the next tab
}
});
});
Also, if you're looking for a cut'n'paste solution, have a look at this multiple-step form validation example: http://jquery.bassistance.de/validate/demo/multipart/
精彩评论