溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

bootstrap-validator如何使用

發(fā)布時(shí)間:2022-03-24 10:01:13 來(lái)源:億速云 閱讀:289 作者:iii 欄目:web開(kāi)發(fā)

本篇內(nèi)容介紹了“bootstrap-validator如何使用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

  需要的js、css和img在下面都有說(shuō)明,耐心點(diǎn)讀!

  需要的js文件:jquery.min.js,bootstrapValidator.min.js,bootstrap-validator-default.js(自定義的一個(gè)默認(rèn)配置文件,是個(gè)人寫(xiě)的,非官方文件)

  前兩個(gè)文件cdn上都有,bootstrap-validator-default.js內(nèi)容如下:

  /*默認(rèn)規(guī)則start*///ip格式$.fn.bootstrapValidator.validators.ip={//message:"ip格式不正確"

  validate:function(validator,$field,options){varvalue=$field.val(),

  ipReg=/^(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/;if(value===''){returntrue;

  }returnipReg.test(value);

  }

  };//password格式$.fn.bootstrapValidator.validators.pw={//message:"必須包含數(shù)字、英文字母、特殊字符"

  validate:function(validator,$field,options){varvalue=$field.val(),

  ipReg=/.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./;

  if(typeofvalue!='string'||!ipReg.test(value)){returnfalse;

  }returntrue;

  }

  };//不允許有空格$.fn.bootstrapValidator.validators.noSpace={//message:"必須包含數(shù)字、英文字母、特殊字符"

  validate:function(validator,$field,options){varvalue=$field.val();if(typeofvalue!='string'||value.indexOf('')>-1){returnfalse;

  }returntrue;

  }

  };//網(wǎng)關(guān)格式$.fn.bootstrapValidator.validators.mask={//message:"網(wǎng)關(guān)不可達(dá)"

  validate:function(validator,$field,options){varipArr=$field.parent().parent().find('input[name="ip"]').val().split('.'),

  gatewayArr=$field.parent().parent().find('input[name="gateway"]').val().split('.'),

  value=$field.val(),

  netmaskArr=value.split('.'),

  len=4,

  i=0;if(ipArr.length!==len||gatewayArr.length!==len||netmaskArr.length!==len){returnfalse;

  }for(;i<len;i++){if((ipArr[i]&netmaskArr[i])!==(gatewayArr[i]&netmaskArr[i])){returnfalse;

  }

  }returntrue;

  }

  };//郵箱表單驗(yàn)證規(guī)則$.fn.bootstrapValidator.validators.mail={//message:"郵箱格式不正確"

  validate:function(validator,$field,options){varmail=/^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/,

  value=$field.val();returnmail.test(value);

  }

  };//電話驗(yàn)證規(guī)則$.fn.bootstrapValidator.validators.phone={//message:"0371-68787027"

  validate:function(validator,$field,options){varphone=/^0\d{2,3}-\d{7,8}$/,

  value=$field.val();returnphone.test(value);

  }

  };//區(qū)號(hào)驗(yàn)證規(guī)則$.fn.bootstrapValidator.validators.ac={//message:"區(qū)號(hào)如:010或0371"

  validate:function(validator,$field,options){varac=/^0\d{2,3}$/,

  value=$field.val();returnac.test(value);

  }

  };//無(wú)區(qū)號(hào)電話驗(yàn)證規(guī)則$.fn.bootstrapValidator.validators.noactel={//message:"電話格式如:68787027"

  validate:function(validator,$field,options){varnoactel=/^\d{7,8}$/,

  value=$field.val();returnnoactel.test(value);

  }

  };/*默認(rèn)規(guī)則end*/$.fn.extend({

  initBV:function(config){//初始化函數(shù)

  if(this.length==0||this[0].tagName!=='FORM'){returnfalse;

  }var$form=this.eq(0),

  $inputs=$form.find('input'),

  $errors=$form.find('.errors'),

  $itemBtn=$form.find('.item-btn');//讓ul.errors中顯示驗(yàn)證項(xiàng)

  functioninitTips(fields){varvalidator,notEmpty,$errField;

  fields=fields.fields||fields;if(!fields)returnfalse;for(varfieldinfields){

  $errField=$form.find('#errors-'+field);

  $errField.hide().find('li').remove();

  validators=fields[field].validators;

  notEmpty=false;for(varvaliinvalidators){

  $('<li/>')

  .addClass('text-left')

  .attr('data-field',field)

  .attr('data-vali',vali)

  .html(validators[vali].message)

  .appendTo($errField);if(vali=='notEmpty'){

  notEmpty=true;

  }

  }if(notEmpty){

  $errField.data('status','error');

  }else{

  $errField.data('status','success');

  }

  }returnfalse;

  }

  initTips(config.fields);

  $form.bootstrapValidator(config)

  .on('success.form.bv',function(e,data){//點(diǎn)擊提交之后

  //Preventformsubmission

  e.preventDefault();returnfalse;

  }).on('success.field.bv',function(e,data){varremoveClass,successClass;if(data.element[0].value){//驗(yàn)證成功

  console.log('realsuccess')

  removeClass='error';

  addClass='success';

  }else{//驗(yàn)證的其實(shí)是''(空字符串),但也被算是success事件

  console.log('notsuccess');

  removeClass='errorsuccess';

  addClass='normal';

  }

  $errors.hide();

  $form.find('#errors-'+data.field).show().data('status','success').find('li').each(function(idx,item){

  $(item).removeClass(removeClass).addClass(addClass);

  });

  }).on('error.field.bv',function(e,data){//data.bv-->TheBootstrapValidatorinstance

  //data.field-->Thefieldname

  //data.element-->Thefieldelement

  //Getthemessagesoffield

  varfield=data.field;varmessages=data.bv.getMessages(data.element);//Removethefieldmessagesifthey'realreadyavailable

  $errors.hide();

  $form.find('#errors-'+data.field).show().data('status','error').find('li').each(function(idx,item){

  item=$(item);if(messages.indexOf(item.text().replace('&','&amp;'))>-1||config.fields[data.field].validators.notEmpty&&messages.indexOf(config.fields[data.field].validators.notEmpty.message)>-1){

  item.removeClass('success').addClass('error');

  }else{

  item.removeClass('error').addClass('success');

  }

  });//Hidethedefaultmessage

  //$field.data('bv.messages')returnsthedefaultelementcontainingthemessages

  data.element

  .data('bv.messages')

  .find('.help-block[data-bv-for="'+data.field+'"]')

  .hide();

  });

  $inputs.blur(function(e){

  $errors.hide();

  })

  $inputs.focus(function(e){

  $errors.hide();

  $(this).trigger('input');

  $(this).parent().find('.totalTip').hide();

  $form.find('#errors-'+this.name).show();

  })

  $itemBtn.click(function(e){

  e.preventDefault();

  $form.find('input').trigger('input');

  $('.errors').hide();returnfalse;

  });

  },

  valiFields:function(fields){//驗(yàn)證fields是否驗(yàn)證通過(guò),未通過(guò)則提示信息

  varstatus=true,

  fieldStatus,$errField,$errFiePar,$totalTip;

  fields=fields.fields||fields;if(!fields)returnfalse;for(varfieldinfields){

  $errField=$('#errors-'+field);

  fieldStatus=$errField.data('status');if(fieldStatus=='error'){

  $errFiePar=$errField.parent(),

  $totalTip=$errFiePar.find('.totalTip');if($totalTip.length){

  $totalTip.show();

  }else{

  $errFiePar.append('<spanclass="totalTiptext-left">'+fields[field].message+'</span>');

  }

  }

  status=status&&fieldStatus=='success';

  }returnstatus;

  }

  });

  需要的css文件:bootstrap-validator-my.css(自定義的一個(gè)默認(rèn)配置文件,是個(gè)人寫(xiě)的,非官方文件)

  bootstrap-validator-my.css內(nèi)容如下:

  *{margin:0;padding:0;box-sizing:border-box;

  }input,button{outline:none;

  }ul{list-style:none;

  }/*字體樣式*/.text-right{text-align:right;

  }.text-left{text-align:left;

  }.text-center,.center{text-align:center;

  }.bold{font-weight:bold;

  }/*位置樣式*/.relative{position:relative;

  }.absolute{position:absolute;

  }.fixed{position:fixed;

  }/*浮動(dòng)相關(guān)*/.float,.float-left{float:left;

  }.float-right{float:right;

  }.clear:after{content:".";display:block;height:0;visibility:hidden;clear:both;

  }.pageWrap{height:auto;min-height:100%;

  }/*panelstart*/.panel{border:1pxsolid#6AC7DC;border-radius:4px;background:#fff;

  }.panel>div:first-child{border-bottom:1pxsolid#6AC7DC;height:35px;line-height:35px;border-radius:4px;

  }.panel.panel-head{padding:020px;position:relative;

  }.panel.panel-head.panel-title{font-weight:bold;

  }.panel.panel-head.panel-btns{position:absolute;right:20px;

  }.panel.panel-head.panel-btnsspan{border-radius:5px;color:#fff;padding:2px8px;

  }.panel.panel-head.panel-btnsspan:hover{cursor:pointer;

  }.panel.panel-head.panel-btns.panel-btn-add{background:#3686D1;

  }.panel.panel-body{padding:20px;

  }.panel.panel-body.panel-table{width:100%;border-collapse:collapse;text-align:center;

  }.panel.panel-body.panel-tabletd,.panel.panel-body.panel-tableth{border:1pxsolid#E0E0E0;font-size:14px;padding:08px;font-style:normal;

  }.panel.panel-body.panel-tableth{height:33px;line-height:33px;

  }.panel.panel-body.panel-tabletd{height:28px;line-height:28px;

  }/*panelend*//*所有表單元素樣式start*/.form{display:flex;justify-content:center;padding:20px;

  }.form.item-txt,.form.item-sel{width:300px;height:30px;line-height:30px;border:1pxsolid#CCCCCC;padding:010px;

  }.form.item-dis{background:#E3E3E3;color:#999999;

  }.form.item-dis:hover{cursor:not-allowed;

  }.form.item{font-size:0;position:relative;margin-bottom:15px;

  }.form.totalTip{position:absolute;left:386px;top:0;width:235px;height:30px;line-height:30px;color:red;

  }.form.errors{width:235px;position:absolute;left:386px;top:0;border:1pxsolid#ddd;box-shadow:1px1px1px#efefef;background:#f9f9f9;padding:5px10px;z-index:100;

  }.form.errorsli{line-height:20px;padding-left:18px;font-size:12px;color:#666;font-family:Tahoma,Helvetica,"MicrosoftYahei","微軟雅黑",Arial,STHeiti;background:url(reg_icons.png)no-repeat-86px-112px;

  }.form.errors.arrow{position:absolute;top:8px;left:-6px;height:0px;width:0px;border-top:6pxsolidtransparent;border-right:6pxsolid#ddd;border-bottom:6pxsolidtransparent;

  }.form.errors.arrow:after{content:'';position:absolute;top:-5px;left:1px;border-top:5pxsolidtransparent;border-right:5pxsolid#f9f9f9;border-bottom:5pxsolidtransparent;

  }.form.errorsli.normal{background-position:-86px-112px;

  }.form.errorsli.success{background-position:-86px-128px;

  }.form.errorsli.error{background-position:-86px-144px;color:red;

  }.form.item*{font-size:14px;

  }.form.item.item-label{display:inline-block;

  }.form.item.item-btn{height:30px;width:300px;line-height:30px;display:inline-block;background:#3686D1;color:#fff;font-weight:bold;text-align:center;

  }.form.item.item-btn:hover{cursor:pointer;

  }.form.error-cont{color:gray;display:inline-block;text-align:left;font-size:12px;height:15px;position:relative;white-space:nowrap;

  }.form.error-cont.icon{position:absolute;top:1px;

  }.form.error-cont.tip{position:absolute;left:20px;font-size:12px;

  }.form.redtip{color:red;font-weight:bold;display:inline-block;height:30px;line-height:30px;

  }/*所有表單元素樣式end*/

  需要的img為:

  3.png

  <!DOCTYPEhtml><html><head>

  <metacharset="utf-8">

  <metaname="viewport"content="width=device-width">

  <title>bootstrap-validator-my</title>

  <linkrel="stylesheet"href="bootstrap-validator-my.css">

  </head><body>

  <divclass="panel">

  <divclass="panel-head">

  </div>

  <divclass="panel-body">

  <formid="defaultForm"role="form"class="form-signinform"action="registerAccount.do"method="post">

  <divclass="text-right">

  <divclass="form-groupitem">

  <labelclass="item-label"for="username">用戶(hù)名:</label>

  <inputclass="form-controlitem-txt"type="text"name="username"id="username"/>

  <ulid="errors-username"data-status=""class="errors"style="display:none;">

  <spanclass="arrow"></span>

  </ul>

  </div>

  <divclass="form-groupitem">

  <labelclass="item-label"for="ip">ip:</label>

  <inputclass="form-controlitem-txt"type="text"name="ip"id="ip"/>

  <ulid="errors-ip"data-status=""class="errors"style="display:none;">

  <spanclass="arrow"></span>

  </ul>

  </div>

  <divclass="form-groupitem">

  <labelclass="item-label"for="password">密碼:</label>

  <inputclass="form-controlitem-txt"type="password"name="password"id="password"/>

  <ulid="errors-password"data-status=""class="errors"style="display:none;">

  <spanclass="arrow"></span>

  </ul>

  </div>

  <divclass="form-groupitem">

  <labelclass="item-label"for="newpassword">新密碼:</label>

  <inputclass="form-controlitem-txt"type="password"name="newpassword"id="newpassword"/>

  <ulid="errors-newpassword"data-status=""class="errors"style="display:none;">

  <spanclass="arrow"></span>

  </ul>

  </div>

  <divclass="form-groupitem">

  <labelclass="item-label"for="repassword">確認(rèn)密碼:</label>

  <inputclass="form-controlitem-txt"type="password"name="repassword"id="repassword"/>

  <ulid="errors-repassword"data-status=""class="errors"style="display:none;">

  <spanclass="arrow"></span>

  </ul>

  </div>

  <divclass="form-groupitem">

  <spanclass="item-btn"type="submit">確認(rèn)注冊(cè)</span>

  </div>

  </div>

  </form>

  </div>

  </div>

  <scriptsrc="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

  <scriptsrc="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>

  <scriptsrc="bootstrap-validator-default.js"></script>

  <script>

  varconfig={fields:{/*驗(yàn)證:規(guī)則*/

  username:{//驗(yàn)證input項(xiàng):驗(yàn)證規(guī)則

  message:'Theusernameisnotvalid',validators:{stringLength:{min:6,max:30,message:'用戶(hù)名長(zhǎng)度必須在6到30之間'

  },regexp:{regexp:/^[a-zA-Z0-9_\.]+$/,message:'用戶(hù)名由數(shù)字字母下劃線和.組成'

  },notEmpty:{message:'用戶(hù)名不能為空'

  }

  }

  },ip:{message:'ip無(wú)效',validators:{ip:{message:'ip格式不正確'

  }

  }

  },password:{message:'密碼無(wú)效',

  validators:{pw:{//regexp:/.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,

  message:'必須包含數(shù)字、英文字母、特殊字符'

  },stringLength:{min:8,message:'密碼長(zhǎng)度須大于等于8位'

  }

  }

  },newpassword:{message:'密碼無(wú)效',validators:{regexp:{regexp:/.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,message:'密碼沒(méi)通過(guò)'

  },stringLength:{min:8,message:'密碼長(zhǎng)度須大于等于8位'

  },different:{//不能和用戶(hù)名相同

  field:'password',//需要進(jìn)行比較的inputname值

  message:'新密碼不能和舊密碼相同'

  },identical:{//相同

  field:'repassword',//需要進(jìn)行比較的inputname值

  message:'新密碼和確認(rèn)密碼要一致'

  }

  }

  },repassword:{message:'密碼無(wú)效',validators:{regexp:{regexp:/.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,message:'密碼沒(méi)通過(guò)'

  },stringLength:{min:8,message:'密碼長(zhǎng)度須大于等于8位'

  },different:{//不能和用戶(hù)名相同

  field:'password',//需要進(jìn)行比較的inputname值

  message:'確認(rèn)密碼不能和舊密碼相同'

  },identical:{//相同

  field:'newpassword',//需要進(jìn)行比較的inputname值

  message:'新密碼和確認(rèn)密碼要一致'

  }

  }

  }

  }

  };var$form=$('#defaultForm');

  $form.initBV(config);

  $form.find('.item-btn').click(function(e){if($form.valiFields(config.fields)){console.log(1)

  }else{console.log(0)

  }

  });</script></body></html>

“bootstrap-validator如何使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI