jquery validate是一個幾乎每個網站都會採用的外掛,
但是常常會因為錯誤訊息讓版面整個錯亂,
最近為了這個問題,找到了qtip2這個外掛,
強力的支援各種jquery plugin的tooptip外掛。
http://craigsworks.com/projects/qtip2/
為了方便使用就支接寫了一個擴充的方法,避免專案太多地方引用重覆的程式碼
原則上只是把範例的程式包起來而已...XD
//移除qtip2
$.validator.prototype.qtipDestory = function(element){
if( $(element).valid()){
$(element).filter(".valid").qtip("destroy");
}
};
//顯示qtip2
$.validator.prototype.qtip = function(error,element,my,at){
// Set positioning based on the elements position in the form
var elem = $(element),
corners = ["right center", "bottom left"],
flipIt = elem.parents("span.right").length > 0;
if(my == "undefined" && at != "undefined"){
corners = [my,at];
}
// Check we have a valid error message
if(!error.is(":empty")) {
// Apply the tooltip only if it isn"t valid
elem.filter(":not(.valid)").qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: "qtip-red" // Make it red... the classic error colour!
}
})
// If we have a tooltip on this element already, just update its content
.qtip("option", "content.text", error);
}
// If the error is empty, remove the qTip
else { elem.qtip("destroy"); }
}
接著就照老樣子在
errorPlacement補上一刀
...省略
errorPlacement:function(error,element){
$your_validated.qtip(error,element);
},
//驗證成功會把qtip消除
success:$.noop,
有時候你需要手動清除qtip(自已遇到關掉dialog要手動清除qtip)
//別忘了reset
$your_validated.resetForm();
$(".qtip").each(function(){
$(this).data("qtip").destroy();
})