表单验证插件--formvalidation

表单验证是一个非常基础的功能,当你的表单项少的时候,可以自己写验证,但是当你的表单有很多的时候,就需要一些验证的插件。今天介绍一款很好用的表单验证插件,formvalidation。其前身叫做bootstrapValidator.

官网:http://formvalidation.io/

下载:目前的最新版本是收费的,但是我们可以下载之前的版本。下载地址:http://down.htmleaf.com/1505/201505101833.zip

下载之后,解压,整个文件夹里面除了最基本的js和css,还包含了很多实例,有兴趣的可以自己去看看。接下来简要介绍一下它的用法。

1.导入包

css:

<link rel="stylesheet"
    href="./static/formvalidation/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
    href="./static/formvalidation/dist/css/formValidation.css">

js:

<script type="text/javascript" src="./static/formvalidation/vendor/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="./static/formvalidation/vendor/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="./static/formvalidation/dist/js/formValidation.js"></script>
    <script type="text/javascript" src="./static/formvalidation/dist/js/framework/bootstrap.js"></script>
    <script type="text/javascript" src="./static/formvalidation/dist/js/language/zh_CN.js"></script>

需要注意的是,即便你已经在项目中导入了bootstrap.js,还是需要再导入上述的bootstrap.js文件,因为它和你之前导入的并不相同。

还有就是即便你已经导入了jquery.min.js,最好还是导入这边的jquery.min.js,因为如果不导入,可能会导致remote类型的验证失效。

2.表单

表单项的填写需要遵从两个原则,表单项的class需标记为:form-control。并且提交按钮的id或者name不要设为sumbit,否则在验证之后会出现无法提交的情况,一个典型的表单如下所示。

 

    <form id="thisForm" method="post" action="">
                <input type="hidden" name="type" value="1" />
                <div class="container-fluid ">
                    <div class="col-xs-12">
                        <div class="panel-body ">
                            <div class="box box-danger box-padding">
                                <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">合伙人账号</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <input type="text" class="form-control" name="partnerName">
                                        </div>

                                    </div>
                                </div>
                                <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">合伙人手机</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <input type="text" class="form-control" name="phone">
                                        </div>

                                    </div>
                                </div>
                                <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">真实名称</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <input type="text" class="form-control" name="realName">
                                        </div>
                                    </div>
                                </div>
                                <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">所属级别</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <select class="form-control" name="partnerLevelId">
                                                <option value="1">市级合伙人</option>
                                                <option value="2">生活馆关注</option>
                                                <option value="3">VIP合伙人</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">上级合伙人</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <select name="parentPartnerId" class="form-control">
                                                <OPTION value="0"></OPTION>
                                                <c:forEach items="${parentPartnerList}" var="parentPartner">
                                                    <option value="${parentPartner.partnerId}">${parentPartner.partnerName}</option>
                                                </c:forEach>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                        <div class="row row-margin">
                                    <div class="col-xs-8 col-xs-offset-1 tipinfo">
                                        <div class="input-group">
                                            <div class="input-group-btn">
                                                <button type="button" class="btn btn-danger">投资金额</button>
                                            </div>
                                            <!-- /btn-group -->
                                            <input type="text" class="form-control" name="joinFee" placeholder="元">
                                        </div>
                                    </div>
                                </div>
                                <div class="row row-margin">
                                    <div class="col-xs-5  col-xs-offset-4">
                                        <button type="button" class="btn btn-default "
                                            onClick="goback();">返回</button>
                                        &nbsp&nbsp
                                        <button type="button" class="btn btn-primary btn-danger"
                                            id="submit1">提交</button>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </form>

 

 

 

3.加载验证器

在页面加载完整之后,通过如下js代码加载验证器。

$(function() {
    $('#thisForm').formValidation({
        message : 'This value is not valid',
        icon : {
            valid : 'glyphicon glyphicon-ok',
            invalid : 'glyphicon glyphicon-remove',
            validating : 'glyphicon glyphicon-refresh'
        },
        fields : {
            partnerName : {
                message : '合伙人名称验证不通过',
                validators : {
                    notEmpty : {
                        message : '不能为空'
                    },
                /*
                 * stringLength: { min: 6, max: 30, message: 'The username must
                 * be more than 6 and less than 30 characters long' },
                 */
                /*
                 * remote: { url: 'remote.php', message: 'The username is not
                 * available' },
                 */
                /*
                 * regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: 'The username
                 * can only consist of alphabetical, number, dot and underscore' }
                 */
                }
            },
            realName : {
                validators : {
                    notEmpty : {
                        message : '不能为空'
                    },
                }
            },
            phone : {
                validators : {
                    notEmpty : {
                        message : '不能为空'
                    },
                    phone : {
                        message : '不是有效的电话号码',
                        country:'CN'
                    },
                     remote: {
                                type: 'POST',
                                url: 'partnerByPhone',
                                message: '该号码已经存在',
                                // delay: 1000
                            }
                }
            },
             joinFee: {
                        validators: {
                            notEmpty: {
                                message:'不能为空'
                                },
                            digits: {
                                message:'不是有效的金额'
                                },
                            greaterThan: {
                                value: 0
                            },
                   
                        }
                    }
        }
    })
});

相信很容易就可以看懂上述验证器的逻辑,就是一个封装好的json对象,以表单的name作为键,对每一个表单规定验证规则,以及验证失败后输出的message。以上列出了几种常见的验证规则,如果想要更多验证规则,可以从下载的文件中去找寻demo.

这里再列出一些比较有用的验证规则,都是我从demo上面摘抄下来的。

--长度要求和正则表达式

   username: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: 'The username is required and can\'t be empty'
                            },
                            stringLength: {
                                min: 6,
                                max: 30,
                                message: 'The username must be more than 6 and less than 30 characters long'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_\.]+$/,
                                message: 'The username can only consist of alphabetical, number, dot and underscore'
                            }
                        }
                    },

--email:

 email: {
                        validators: {
                            notEmpty: {
                                message: 'The email address is required and can\'t be empty'
                            },
                            emailAddress: {
                                message: 'The input is not a valid email address'
                            }
                        }
                    },

--电话

      phone: {
                    validators: {
                        notEmpty: {
                            message: '不能为空'
                        },
                        phone:{
                             message: '不是合法电话',
                             country:'CN'
                        }
              
                }
            }

--网站

 website: {
                        validators: {
                            uri: {
                                message: 'The input is not a valid URL'
                            }
                        }
                    }

--邮编

  zipCode: {
                        validators: {
                            zipCode: {
                                country: 'CN',//中国邮编
                                message: 'The input is not a valid US zip code'
                            }
                        }
                    }

--密码及确认

      password: {
                        validators: {
                            notEmpty: {
                                message: 'The password is required and can\'t be empty'
                            }
                        }
                    },
                    confirmPassword: {
                        validators: {
                            notEmpty: {
                                message: 'The confirm password is required and can\'t be empty'
                            },
                            identical: {
                                field: 'password',
                                message: 'The password and its confirm are not the same'
                            }
                        }
                    },

--数字

   age: {
                        validators: {
                            notEmpty: {},
                            digits: {},
                            greaterThan: {
                                value: 18
                            },
                            lessThan: {
                                value: 100
                            }
                        }
                    },

 --整数

  'limitPromotion.stock': {
                        validators: {
                            notEmpty: {
                                message:'不能为空'
                                },
                               regexp: {
                                regexp: /^([0-9][0-9]*)$/,
                                message: '必须为整数'
                            }
                   
                        }
             },

 --日期

'employee.birthday' : {
                message : '表单校验失败',
                validators : {
                    notEmpty : {
                        message : '不能为空'
                    },
                    //日期格式
                     date: {
                                format: 'YYYY-MM-DD hh:mm:ss',
                                message : '不是合法的日期'
                            }
                }
            },

 

--远程调用

  username: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: 'The username is required and can\'t be empty'
                            },
                            remote: {
                                type: 'POST',
                                url: 'partnerByPhone',
                                message: '电话号码已使用',
                                //delay: 1000
                            }
                        }
                    }

关于远程调用就是需要去访问服务端的接口,来验证输入的表单是否有效,经常出现的场景是我们需要验证一个用户名是否已经被注册过了。该远程调用返回的响应是一个json的数据,如果是{ “valid”: true }表示通过验证,否则{ “valid”: false}表示验证失败。

其中服务端的代码示例如下:

    @ResponseBody
    @RequestMapping("partnerByPhone")
    public Map<String, Object> partnerByPhone(String phone) {
        TPartner partner = partnerService.getPartnerByPhone(phone);
        Map<String, Object> maps = new HashMap<String, Object>();
        if (partner == null) {
            maps.put("valid", true);
        } else {
            maps.put("valid", false);
        }
        return maps;
    }

 

4.提交表单时候手动调用验证

一般情况下,当我们提交表单的时候,需要手动调用验证,可以用如下代码来实现。针对上述表单。

 
  
  $("#submit1").click(function() {
        var $form = $("#thisForm");
        var bv = $form.data('formValidation'); bv.validate(); if(bv.isValid()){ $.ajax({ type:'post', url:'partnerSave', data:$('#thisForm').serialize(), dataType:'html', success:function(data){ if(data>0){ alert("成功"); location.href="partnerHome"; }else{ alert("失败"); } } }); } });
 
 

怎么样,就是这么简单。我们来看看效果吧。当然提示错误的语言和一些标签的样式你可以自己去修改。

 

 

 

 总的来说,这还是一款比较容易上手的验证器,有需要的朋友可以尝试一下。

 

转载于:https://www.cnblogs.com/roy-blog/p/8275524.html

jQuery formValidator表单验证插件,它是基于jQuery类库,实现了js脚本于页面html代码的分离。你可以划分多个校验组,每个组的校验都是互不影响。对一个表单对象,你只需要写一行代码就可以轻松实现无数种脚本控制。jQuery formValidator表单插件致力于改善重复编程、考虑浏览器兼容性等情况;你只关心业务逻辑,而无需关心实现过程,只需简单的配置,无需写代码就能实现表单的检验。 jQuery formValidator表单校验插件 4.1.0 升级内容: 新增以下功能: 1、新增换肤功能,包括提示层的样式、输入控件(目前只支持text、password、file、textarea)的样式。initConfig增加theme属性,表示皮肤名,theme的值可取目录theme下的文件夹名。详见电子版帮助文件里的【制作皮肤】 2、formvalidator函数增加属性leftTrim和rightTrim。是否去掉左边或右边的空格,默认值false 3、ajaxValidator的success事件,可以返回字符串,表示错误信息,将显示在提示层上。 4、为initConfig增加属性ajaxForm,用于配置整个表单ajax提交的参数,详见demo7和api帮助 $.formValidator.initConfig({theme:"Default",submitOnce:true,formID:"form1",ajaxForm:{ dataType : "html", buttons:$("#button"), url: "http://www.51gh.net/chkuser.aspx?act=ok" }}); 5、所有函数的onError和onSuccess支持字符串,也支持函数(参数为当前的值)返回字符串。 6、发布网页版代码生成器,从当前版本开始支持。 解决以下BUG: 1、修正ajaxValidator函数有一处条件书写错误的BUG。 2、修正formvalidator函数autoModify属性对password控件不起作用的BUG。 调用步骤: a、在你要校验的表单页面中引入代码生成器的脚本。 b、调用函数。如果已经写了校验代码,请在校验代码注册完成后调用。 $.formValidatorTools.openTools(); 压缩包相关变更 1、所有的帮助、范例制作成了chm电子帮助文件 2、插件相关的文件放一个目录里 插件支持5种大的校验方式,分别是:inputValidator(针对input、textarea、select控件的字符长度、值范围、选择个数的控制)、compareva lidator(提供2个对象的比较,目前可以比较字符串和数值型)、ajaxValidator(通过ajax到服务器上做数据校验)、regexValidator(提供可扩展的正则表达式库) 、functionValidator (可使用外部函数来做校验,可以当做过程处理)。插件支持四种提示模式:固定提示层(FixTip)、自动构建提示层(AutoTip)、单个提示层跟随(SingleTip)、弹出提示内容(AlertTip)。插件支持换肤:默认情况下提供4套皮肤,其中包括58网、网易邮箱注册两套皮肤。 本插件于其他校验控件最大的区别有6点: 1、校验功能可以扩展。    对中文、英文、数字、整数、实数、Email地址格式、基于HTTP协议的网址格式、电话号码格式、手机号码格式、货币格式、邮政编码、身份证号码、QQ号码、日期等等这些控制,别的表单校验控件是代码里写死的,而formValidator是通过外部js文件来扩展的,你可以通过写正则表达式和函数来无限的扩展这些功能。 2、实现了校验代码于html代码的完全分离。    你的所有信息都无需配置在校验表单元素上,你只要在js上配置你的信息。使美工(界面)和JavaScript工程师的工作不交织在一起 3、你只需写一行代码就能完成一个表单元素的所有校验。你只需要写一行代码就能完成一下所有的控制 •支持所有类型客户端控件的校验 •支持jQuery所有的选择器语法,只要控件有唯一ID和type属性 •支持函数和正则表达式的扩展。提供扩展库formValidatorReg.js,你可以自由的添加、修改里面的内容。 •支持2种校验模式。第一种:文字提示(showword模式);第二种:弹出窗口提示(showalert模式) •支持多个校验组。如果一个页面有多个提交按钮,分别做不同得提交,提交前要做不同的校验,所以你得用到校验组的功能。 •支持4种状态的信息提示功能,可以
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值