搜索
首页web前端html教程bootstrap-validator使用详解(代码实例)

bootstrap-validator使用详解(代码实例)

Mar 09, 2018 am 10:43 AM
使用详解

这次给大家带来bootstrap-validator使用详解,使用bootstrap-validator的注意事项有哪些,下面就是实战案例,一起来看一下。

【相关视频推荐:Bootstrap教程

1.png

2.png

需要的js、css和img在下面都有说明,耐心点读!
需要的js文件: jquery.min.js,bootstrapValidator.min.js,bootstrap-validator-default.js(自定义的一个默认配置文件,是个人写的,非官方文件)
前两个文件cdn上都有,bootstrap-validator-default.js内容如下:

/*默认规则 start*///ip格式$.fn.bootstrapValidator.validators.ip = {    //message: "ip格式不正确"
    validate: function(validator, $field, options) {        var value = $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 === '') {            return true;
        }        return ipReg.test(value);
    }
};//password格式$.fn.bootstrapValidator.validators.pw = {    //message: "必须包含数字、英文字母、特殊字符"
    validate: function(validator, $field, options) {        var value = $field.val(),
            ipReg = /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./;
        if (typeof value != 'string' || !ipReg.test(value)) {            return false;
        }        return true;
    }
};//不允许有空格$.fn.bootstrapValidator.validators.noSpace = {    //message: "必须包含数字、英文字母、特殊字符"
    validate: function(validator, $field, options) {        var value = $field.val();        if (typeof value != 'string' || value.indexOf(' ') > -1) {            return false;
        }        return true;
    }
};//网关格式$.fn.bootstrapValidator.validators.mask = {    //message: "网关不可达"
    validate: function(validator, $field, options) {        var ipArr = $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) {            return false;
        }        for (; i < len; i++) {            if ((ipArr[i] & netmaskArr[i]) !== (gatewayArr[i] & netmaskArr[i])) {                return false;
            }
        }        return true;
    }
};//邮箱 表单验证规则$.fn.bootstrapValidator.validators.mail = {    //message: "邮箱格式不正确"
    validate: function(validator, $field, options) {        var mail = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/,
            value = $field.val();        return mail.test(value);
    }
};//电话验证规则$.fn.bootstrapValidator.validators.phone = {    //message: "0371-68787027"
    validate: function(validator, $field, options) {        var phone = /^0\d{2,3}-\d{7,8}$/,
            value = $field.val();        return phone.test(value);
    }
};//区号验证规则$.fn.bootstrapValidator.validators.ac = {    //message: "区号如:010或0371"
    validate: function(validator, $field, options) {        var ac = /^0\d{2,3}$/,
            value = $field.val();        return ac.test(value);
    }
};//无区号电话验证规则$.fn.bootstrapValidator.validators.noactel = {    //message: "电话格式如:68787027"
    validate: function(validator, $field, options) {        var noactel = /^\d{7,8}$/,
            value = $field.val();        return noactel.test(value);
    }
};/*默认规则 end*/$.fn.extend({
    initBV: function(config) { //初始化函数
        if (this.length == 0 || this[0].tagName !== &#39;FORM&#39;) {            return false;
        }        var $form = this.eq(0),
            $inputs = $form.find(&#39;input&#39;),
            $errors = $form.find(&#39;.errors&#39;),
            $itemBtn = $form.find(&#39;.item-btn&#39;);        //让ul.errors中显示验证项
        function initTips(fields) {            var validator, notEmpty, $errField;

            fields = fields.fields || fields;            if (!fields) return false;            for (var field in fields) {
                $errField = $form.find(&#39;#errors-&#39; + field);
                $errField.hide().find(&#39;li&#39;).remove();
                validators = fields[field].validators;
                notEmpty = false;                for (var vali in validators) {
                    $(&#39;<li/>&#39;)
                        .addClass(&#39;text-left&#39;)
                        .attr(&#39;data-field&#39;, field)
                        .attr(&#39;data-vali&#39;, vali)
                        .html(validators[vali].message)
                        .appendTo($errField);                    if (vali == &#39;notEmpty&#39;) {
                        notEmpty = true;
                    }
                }                if (notEmpty) {
                    $errField.data(&#39;status&#39;, &#39;error&#39;);
                } else {
                    $errField.data(&#39;status&#39;, &#39;success&#39;);
                }
            }            return false;
        }

        initTips(config.fields);

        $form.bootstrapValidator(config)
            .on(&#39;success.form.bv&#39;, function(e, data) { //点击提交之后
                // Prevent form submission
                e.preventDefault();                return false;
            }).on(&#39;success.field.bv&#39;, function(e, data) {                var removeClass, successClass;                if (data.element[0].value) {                    //验证成功
                    console.log(&#39;real success&#39;)
                    removeClass = &#39;error&#39;;
                    addClass = &#39;success&#39;;
                } else {                    //验证的其实是&#39;&#39;(空字符串),但也被算是success事件
                    console.log(&#39;not success&#39;);
                    removeClass = &#39;error success&#39;;
                    addClass = &#39;normal&#39;;
                }
                $errors.hide();
                $form.find(&#39;#errors-&#39; + data.field).show().data(&#39;status&#39;, &#39;success&#39;).find(&#39;li&#39;).each(function(idx, item) {
                    $(item).removeClass(removeClass).addClass(addClass);
                });
            }).on(&#39;error.field.bv&#39;, function(e, data) {                // data.bv      --> The BootstrapValidator instance
                // data.field   --> The field name
                // data.element --> The field element

                // Get the messages of field
                var field = data.field;                var messages = data.bv.getMessages(data.element);                // Remove the field messages if they&#39;re already available
                $errors.hide();
                $form.find(&#39;#errors-&#39; + data.field).show().data(&#39;status&#39;, &#39;error&#39;).find(&#39;li&#39;).each(function(idx, item) {
                    item = $(item);                    if (messages.indexOf(item.text().replace(&#39;&&#39;, &#39;&amp;&#39;)) > -1 || config.fields[data.field].validators.notEmpty && messages.indexOf(config.fields[data.field].validators.notEmpty.message) > -1) {
                        item.removeClass(&#39;success&#39;).addClass(&#39;error&#39;);
                    } else {
                        item.removeClass(&#39;error&#39;).addClass(&#39;success&#39;);
                    }
                });                // Hide the default message
                // $field.data(&#39;bv.messages&#39;) returns the default element containing the messages
                data.element
                    .data(&#39;bv.messages&#39;)
                    .find(&#39;.help-block[data-bv-for="&#39; + data.field + &#39;"]&#39;)
                    .hide();
            });

        $inputs.blur(function(e) {
            $errors.hide();
        })
        $inputs.focus(function(e) {
            $errors.hide();
            $(this).trigger(&#39;input&#39;);
            $(this).parent().find(&#39;.totalTip&#39;).hide();
            $form.find(&#39;#errors-&#39; + this.name).show();
        })
        $itemBtn.click(function(e) {
            e.preventDefault();
            $form.find(&#39;input&#39;).trigger(&#39;input&#39;);
            $(&#39;.errors&#39;).hide();            return false;
        });
    },
    valiFields: function(fields) { //验证fields是否验证通过,未通过则提示信息
        var status = true,
            fieldStatus, $errField, $errFiePar, $totalTip;

        fields = fields.fields || fields;        if (!fields) return false;        for (var field in fields) {
            $errField = $(&#39;#errors-&#39; + field);
            fieldStatus = $errField.data(&#39;status&#39;);            if (fieldStatus == &#39;error&#39;) {
                $errFiePar = $errField.parent(),
                    $totalTip = $errFiePar.find(&#39;.totalTip&#39;);                if ($totalTip.length) {
                    $totalTip.show();
                } else {
                    $errFiePar.append(&#39;<span class="totalTip text-left">&#39; + fields[field].message + &#39;</span>&#39;);
                }
            }
            status = status && fieldStatus == &#39;success&#39;;
        }        return status;
    }
});

需要的css文件: bootstrap-validator-my.css(自定义的一个默认配置文件,是个人写的,非官方文件)
bootstrap-validator-my.css内容如下:

* {    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;
}/*浮动相关*/.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%;
}/*panel start*/.panel {    border: 1px solid #6AC7DC;    border-radius: 4px;    background: #fff;
}.panel>div:first-child {    border-bottom: 1px solid #6AC7DC;    height: 35px;    line-height: 35px;    border-radius: 4px;
}.panel .panel-head {    padding: 0 20px;    position: relative;
}.panel .panel-head .panel-title {    font-weight: bold;
}.panel .panel-head .panel-btns {    position: absolute;    right: 20px;
}.panel .panel-head .panel-btns span {    border-radius: 5px;    color: #fff;    padding: 2px 8px;
}.panel .panel-head .panel-btns span: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-table td,.panel .panel-body .panel-table th {    border: 1px solid #E0E0E0;    font-size: 14px;    padding: 0 8px;    font-style: normal;
}.panel .panel-body .panel-table th {    height: 33px;    line-height: 33px;
}.panel .panel-body .panel-table td {    height: 28px;    line-height: 28px;
}/*panel end*//*所有表单元素样式 start*/.form {    display: flex;    justify-content: center;    padding: 20px;
}.form .item-txt,.form .item-sel {    width: 300px;    height: 30px;    line-height: 30px;    border: 1px solid #CCCCCC;    padding: 0 10px;
}.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: 1px solid #ddd;    box-shadow: 1px 1px 1px #efefef;    background: #f9f9f9;    padding: 5px 10px;    z-index: 100;
}.form .errors li {    line-height: 20px;    padding-left: 18px;    font-size: 12px;    color: #666;    font-family: Tahoma,Helvetica,"Microsoft Yahei","微软雅黑",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: 6px solid transparent;    border-right: 6px solid #ddd;    border-bottom: 6px solid transparent;
}.form .errors .arrow:after {    content: &#39;&#39;;    position: absolute;    top: -5px;    left: 1px;    border-top: 5px solid transparent;    border-right: 5px solid #f9f9f9;    border-bottom: 5px solid transparent;
}.form .errors li.normal {    background-position: -86px -112px;
}.form .errors li.success {    background-position: -86px -128px;
}.form .errors li.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

<!DOCTYPE html><html><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>bootstrap-validator-my</title>
    <link rel="stylesheet" href="bootstrap-validator-my.css">
    </head><body>
    <div class="panel">
        <div class="panel-head">
        </div>
        <div class="panel-body">
            <form id="defaultForm" role="form" class="form-signin form" action="registerAccount.do" method="post">
                <div class="text-right">
                    <div class="form-group item">
                        <label class="item-label" for="username">用户名:</label>
                        <input class="form-control item-txt" type="text" name="username" id="username" />
                        <ul id="errors-username" data-status="" class="errors" style="display: none;">
                            <span class="arrow"></span>
                        </ul>
                    </div>
                    <div class="form-group item">
                        <label class="item-label" for="ip">ip:</label>
                        <input class="form-control item-txt" type="text" name="ip" id="ip" />
                        <ul id="errors-ip" data-status="" class="errors" style="display: none;">
                            <span class="arrow"></span>
                        </ul>
                    </div>
                    <div class="form-group item">
                        <label class="item-label" for="password">密码:</label>
                        <input class="form-control item-txt" type="password" name="password" id="password" />
                        <ul id="errors-password" data-status="" class="errors" style="display: none;">
                            <span class="arrow"></span>
                        </ul>
                    </div>
                    <div class="form-group item">
                        <label class="item-label" for="newpassword">新密码:</label>
                        <input class="form-control item-txt" type="password" name="newpassword" id="newpassword" />
                        <ul id="errors-newpassword" data-status="" class="errors" style="display: none;">
                            <span class="arrow"></span>
                        </ul>
                    </div>
                    <div class="form-group item">
                        <label class="item-label" for="repassword">确认密码:</label>
                        <input class="form-control item-txt" type="password" name="repassword" id="repassword" />
                        <ul id="errors-repassword" data-status="" class="errors" style="display: none;">
                            <span class="arrow"></span>
                        </ul>
                    </div>
                    <div class="form-group item">
                        <span class="item-btn" type="submit">确认注册</span>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>
    <script src="bootstrap-validator-default.js"></script>
    <script>

    var config = {        fields: { /*验证:规则*/
            username: { //验证input项:验证规则
                message: &#39;The username is not valid&#39;,                validators: {                    stringLength: {                        min: 6,                        max: 30,                        message: &#39;用户名长度必须在6到30之间&#39;
                    },                    regexp: {                        regexp: /^[a-zA-Z0-9_\.]+$/,                        message: &#39;用户名由数字字母下划线和.组成&#39;
                    },                    notEmpty: {                        message: &#39;用户名不能为空&#39;
                    }
                }
            },            ip: {                message: &#39;ip无效&#39;,                validators: {                    ip: {                        message: &#39;ip格式不正确&#39;
                    }
                }
            },            password: {                message: &#39;密码无效&#39;,                
                validators: {                    pw: {                        // regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,
                        message: &#39;必须包含数字、英文字母、特殊字符&#39;
                    },                    stringLength: {                        min: 8,                        message: &#39;密码长度须大于等于8位&#39;
                    }
                }
            },            newpassword: {                message: &#39;密码无效&#39;,                validators: {                    regexp: {                        regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,                        message: &#39;密码没通过&#39;
                    },                    stringLength: {                        min: 8,                        message: &#39;密码长度须大于等于8位&#39;
                    },                    different: { //不能和用户名相同
                        field: &#39;password&#39;, //需要进行比较的input name值
                        message: &#39;新密码不能和旧密码相同&#39;
                    },                    identical: { //相同
                        field: &#39;repassword&#39;, //需要进行比较的input name值
                        message: &#39;新密码和确认密码要一致&#39;
                    }
                }
            },            repassword: {                message: &#39;密码无效&#39;,                validators: {                    regexp: {                        regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./,                        message: &#39;密码没通过&#39;
                    },                    stringLength: {                        min: 8,                        message: &#39;密码长度须大于等于8位&#39;
                    },                    different: { //不能和用户名相同
                        field: &#39;password&#39;, //需要进行比较的input name值
                        message: &#39;确认密码不能和旧密码相同&#39;
                    },                    identical: { //相同
                        field: &#39;newpassword&#39;, //需要进行比较的input name值
                        message: &#39;新密码和确认密码要一致&#39;
                    }
                }
            }
        }
    };    var $form = $(&#39;#defaultForm&#39;);
    $form.initBV(config);
    $form.find(&#39;.item-btn&#39;).click(function(e) {        if($form.valiFields(config.fields)) {            console.log(1)
        }else {            console.log(0)
        }
    });    </script></body></html>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

sublime怎样快速的创建html头部代码

JS中的常用函数汇总

HTML5的集合

用4a249f0d628e2318394fd9b75b4636b1和段落e388a4556c0f65e1904146cc1a846bee 写一个三毛语录

以上是bootstrap-validator使用详解(代码实例)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
HTML标签和HTML属性有什么区别?HTML标签和HTML属性有什么区别?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

HTML的未来:进化和趋势HTML的未来:进化和趋势May 13, 2025 am 12:01 AM

HTML的未来将朝着更加语义化、功能化和模块化的方向发展。1)语义化将使标签更明确地描述内容,提升SEO和无障碍访问。2)功能化将引入新元素和属性,满足用户需求。3)模块化将支持组件化开发,提高代码复用性。

为什么HTML属性对Web开发很重要?为什么HTML属性对Web开发很重要?May 12, 2025 am 12:01 AM

htmlattributesarecrucialinwebdevelopment forcontrollingBehavior,外观和功能

Alt属性的目的是什么?为什么重要?Alt属性的目的是什么?为什么重要?May 11, 2025 am 12:01 AM

alt属性是HTML中标签的重要部分,用于提供图片的替代文本。1.当图片无法加载时,alt属性中的文本会显示,提升用户体验。2.屏幕阅读器使用alt属性帮助视障用户理解图片内容。3.搜索引擎索引alt属性中的文本,提高网页的SEO排名。

HTML,CSS和JavaScript:示例和实际应用HTML,CSS和JavaScript:示例和实际应用May 09, 2025 am 12:01 AM

HTML、CSS和JavaScript在网页开发中的作用分别是:1.HTML用于构建网页结构;2.CSS用于美化网页外观;3.JavaScript用于实现动态交互。通过标签、样式和脚本,这三者共同构筑了现代网页的核心功能。

如何在标签上设置lang属性?为什么这很重要?如何在标签上设置lang属性?为什么这很重要?May 08, 2025 am 12:03 AM

设置标签的lang属性是优化网页可访问性和SEO的关键步骤。1)在标签中设置lang属性,如。2)在多语言内容中,为不同语言部分设置lang属性,如。3)使用符合ISO639-1标准的语言代码,如"en"、"fr"、"zh"等。正确设置lang属性可以提高网页的可访问性和搜索引擎排名。

HTML属性的目的是什么?HTML属性的目的是什么?May 07, 2025 am 12:01 AM

htmlattributeseresene forenhancingwebelements'functionalityandAppearance.TheyAdDinformationTodeFineBehavior,外观和互动,使网站互动,响应式,visalalyAppealing.AttributesLikutesLikeSlikEslikesrc,href,href,href,类,类型,类型,和dissabledtransfransformformformformformformformformformformformformformformforment

您如何在HTML中创建列表?您如何在HTML中创建列表?May 06, 2025 am 12:01 AM

toCreateAlistinHtml,useforforunordedlistsandfororderedlists:1)forunorderedlists,wrapitemsinanduseforeachItem,RenderingeringAsabulleTedList.2)fororderedlists,useandfornumberedlists,useandfornumberedlists,casundfornumberedlists,customeizableWithTheTtheTthetTheTeTeptTributeFordTributeForderForderForderFerentNumberingSnumberingStyls。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。