妙用Bootstrap的 popover插件實現(xiàn)校驗表單提示功能
最近的項目,用Bootstrap比較多。瀏覽Bootstrap文檔,發(fā)現(xiàn) popover 插件特別適合做表單校驗出錯的提示。
因為使的非常頻繁,最近把它封住下,做成 jQuery的插件。 通過 本插件,在 html標(biāo)簽中 定義好 data-vaild=”校驗正則” data-errmsg=”錯誤信息即可”。為什么 要把 校驗規(guī)則 寫到 html 標(biāo)簽中呢?因為 我還用它做了 后臺 的校驗規(guī)則(后臺沒用Node,現(xiàn)在用的ASP,忙完專門再發(fā)文寫下原理)。
<input class="form-control" id="u_exam_idnumber" name="u_exam_idnumber" placeholder="請輸入中考準(zhǔn)考證號" data-vaild="^\d{5,20}$" data-errmsg="準(zhǔn)考證號碼不正確,僅能包含數(shù)字"
最終實現(xiàn)的效果如下:

插件代碼如下:
"use strict";
/*
jQuery+Bootstrap 校驗表單 by Miaoqiyuan.cn
原理:http://www.miaoqiyuan.cn/p/jquery-bootstrap-vaild
演示:http://www.miaoqiyuan.cn/products/vaild/index.html
源碼:http://www.miaoqiyuan.cn/products/vaild/jQuery.Vaild.js
*/
(function(jQuery){
$.extend({
Vaild : function(_this){
if( !!$(_this).data("vaild") ){
var pattern = new RegExp($(_this).data("vaild"));
if( pattern.test( $(_this).val() ) ){
$(_this).parent().removeClass("has-error").addClass("has-success");
$(_this).popover("destroy");
}else{
$(_this).parent().addClass("has-error").removeClass("has-success");
$(_this).data("toogle", "top").data("placement", "top").data("container", "body").data("content", $(_this).data("errmsg")).popover({"trigger":"manual"}).popover("show");
return false;
}
}else{
$(_this).parent().addClass("has-success");
}
return true;
}
});
$.fn.extend({
Vaild : function(){
$(this).each(function(index, _this){
$(_this).submit(function(){
var checkResult = true;
for(var i = 0 ; i < _this.length; i++ ){
checkResult = $.Vaild(_this[i]) && checkResult;
}
return checkResult;
});
for(var i = 0 ; i < _this.length; i++ ){
$(_this[i]).blur(function(){
$.Vaild(this);
});
}
});
}
});
})(jQuery);
調(diào)用的時候非常簡單,直接使用以下代碼:
<script>
$("form").Vaild();
</script>
當(dāng)表單失去焦點時,如果不合法,會直接提示錯誤。點擊提交時,如果有表單項目不合法,會阻止表單繼續(xù)提交。
popoover默認的背景是 白色的,不能起到 警示作用,而且 padding 設(shè)置過大,太占用空間了。 最后調(diào)整下CSS,就實現(xiàn)了 截圖的效果。
/*重構(gòu) popover */
.popover{background:#C00;color:#FFF;}
.popover .popover-content{padding:1px 5px;}
.popover.top>.arrow:after{border-top-color:#C00;}
/*重構(gòu) bootstrap 默認錯誤提示 */
.has-error input,
.has-error textarea,
.has-error select{background-color:#F2DEDE;}
.has-success input,
.has-success textarea,
.has-success select{background-color:#DFF0D8}
以上所述是小編給大家介紹的Bootstrap的 popover插件實現(xiàn)校驗表單提示功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
初學(xué)js插入節(jié)點appendChild insertBefore使用方法
由于可見insertBefore()方法的特性是在已有的子節(jié)點前面插入新的節(jié)點但是兩種情況結(jié)合起來發(fā)現(xiàn)insertBefore()方法插入節(jié)點,是可以在子節(jié)點列表的任意位置。2011-07-07
JavaScript進階教程之函數(shù)的定義、調(diào)用及this指向問題詳解
這篇文章主要給大家介紹了關(guān)于JavaScript進階教程之函數(shù)的定義、調(diào)用及this指向問題的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用js具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-09-09

