使用JS验证密码的强度 jQuery验证框架

密码强度评分,根据得分显示密码强度。
function testpass(password,username){
    var score = 0;
    if (password.length < 4 ) { return -4; }
    if (typeof(username) != 'undefined' && password.toLowerCase() == username.toLowerCase()){return -2}
    score += password.length * 4;
    score += ( repeat(1,password).length - password.length ) * 1;
    score += ( repeat(2,password).length - password.length ) * 1;
    score += ( repeat(3,password).length - password.length ) * 1;
    score += ( repeat(4,password).length - password.length ) * 1;
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ score += 5;}
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){ score += 10;}
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){ score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){ score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){score += 15;}
    if (password.match(/^\w+$/) || password.match(/^\d+$/) ){ score -= 10;}
    if ( score < 0 ){score = 0;}
    if ( score > 100 ){ score = 100;}
    return score;
    
    function repeat(len,str){
    var res = "";
    for (var i = 0; i < str.length; i++ ){
        var repeated = true;
        for (var j = 0, max = str.length - i - len; j < len && j < max; j++){
            repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + len));
        }
        if (j < len) repeated = false;
        if (repeated) {
            i += len - 1;
            repeated = false;
        }else{
            res += str.charAt(i);
        }
    }
    return res;
    }
}

通过上述函数可对密码进行评分验证。
举例:
function checkpass(pass){
    var username = document.getElementById('username').value;
    var score = testpass(pass.value,username);
    var password_label = document.getElementById('password_label');
    if(score == -4)    {
        password_label.innerHTML = '太短';
    }else if(score == -2){
        password_label.innerHTML = '与用户名相同';
    }else{
        var color = score < 34 ? '#edabab' : (score < 68 ? '#ede3ab' : '#d3edab');
        var text = score < 34 ? '弱' : (score < 68 ? '一般' : '很好');
        var width = score + '%';
        password_label.innerHTML = "<span style='width:"+width+";display:block;overflow:hidden;height:20px;line-height:20px;background:"+color+";'>"+text+"</span>";
    }
}
</script>
请输入用户名:<br>
<input type="text" class="inpt" name="username" style="width:160px" id="username" /><br>
请输入密码:<br>
<input type="password" class="inpt" style="width:160px" οnkeyup="javascript:checkpass(this)" name="pass" id="pass" /><br>
<span id="password_label" style="width:160px;border:1px solid #F0F0F0"></span>

 

jquery验证表单很简单的方法
现在网上有很多jquery验证表单的插件,但都写的比较复杂。一般都有两三个文件。
我今天写一个最简单但是很实用的验证登录表单的方法。
我基本上只是给大家提供一种思路。jquery插件一般也是按这个思路写的。
大家可以按这个思路去扩展,不过只要实用越简单越好

代码如下

<script type="text/javascript">
 //首先要加载jquery库文件,因为这里只是给大家演示,所以我就不加载了。
 //下面为jquery代码
 $(function(){
     $("#name").blur(function(){//用户名文本框失去焦点触发验证事件
        if(!$(this).val || !$(this).val.match(/([w]){2,15}$/))//只处验证不能为空并且只能为英文或者数字或者下划线组成的2-15个字符
        {
            $("#nameTip").html("用户名不能为空且只能为英文或者数字");
        }
        else
        {
            $("#nameTip").html("输入正确");
        }

     });

      $("#pas1").blur(function(){//用户名文本框失去焦点触发验证事件
        if(!$(this).val || !$(this).val.match(/([w]){2,15}$/))//只处验证和上面一样
        {
            $("#pas1").html("密码不能为空且只能为英文或者数字");
        }
        else
        {
            $("#pas1").html("输入正确");
        }

     });
     $("#pas2").blur(function(){//用户名文本框失去焦点触发验证事件
        if(!$(this).val || $(this).val() != $("#pas1").val() )//只处验证和上面一样
        {
            $("#pas2").html("密码为空或者和上面的密码不致");
        }
        else
        {
            $("#pas2").html("输入正确");
        }

     });

})
 </script>
  <form action="#">
    用户名:<input type="text" id="name" /><span id="nameTip"></span>
    密码:<input type="password" id="pas1" /><span id="pas1Tip"></span>
    确认密码:<input type="password" id="pas2" /><span id="pas2Tip"></span>
    <input type="submit" value="提交" />
  </form>

[1] 验证页面
Html代码 复制代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>  
  2. <html>  
  3.   <head>  
  4.     <title>jquery验证框架</title>  
  5.     <link rel="stylesheet" type="text/css" href="css/index.css">  
  6.     <script type="text/javascript" src=js/jquery-1.3.2.min.js></script>  
  7.     <script type="text/javascript" src=js/jquery.validate.pack.js></script>  
  8.     <script type="text/javascript" src=js/jquery.form.js></script>  
  9.     <script type="text/javascript" src=js/valid.js></script>  
  10.     <style type="text/css">  
  11.         label { width: 10em; float: left; }   
  12.         label.haha {color: red; padding-left: 18px; vertical-align: top;width: 196px; background: url("images/unchecked.gif") no-repeat;}   
  13.         input.haha { border: 1px solid red; }   
  14.         label.valid {background: url("images/checked.gif") no-repeat; color: #065FB9;}   
  15.         input.focus { border: 2px solid green; }   
  16.         ul li{ display: block;}   
  17.     </style>  
  18.   </head>  
  19.      
  20.   <body>  
  21.      
  22.   <div id="form_con">  
  23.         <form class="cmxform" id="myform" method="post" action="">  
  24.             <table cellspacing="0" cellpadding="0">  
  25.                 <tbody>  
  26.                     <tr>  
  27.                         <td>用户名</td>  
  28.                         <td><input type="text" name="username" class="required" /></td>  
  29.                         <td></td>  
  30.                     </tr>  
  31.                     <tr>  
  32.                         <td>密码</td>  
  33.                         <td><input id="password" type="password" name="firstpwd" /></td>  
  34.                         <td></td>  
  35.                     </tr>  
  36.                     <tr>  
  37.                         <td>验证密码</td>  
  38.                         <td><input type="password" name="secondpwd" /></td>  
  39.                         <td></td>  
  40.                     </tr>  
  41.                     <tr>  
  42.                         <td>性别</td>  
  43.                         <td><input id="sex" type="radio" name="sex" /><input type="radio" name="sex" /></td>  
  44.                         <td></td>  
  45.                     </tr>  
  46.                     <tr>  
  47.                         <td>年龄</td>  
  48.                         <td><input type="text" name="age" /></td>  
  49.                         <td></td>  
  50.                     </tr>  
  51.                     <tr>  
  52.                         <td>邮箱</td>  
  53.                         <td><input type="text" name="email" /></td>  
  54.                         <td></td>  
  55.                     </tr>  
  56.                     <tr>  
  57.                         <td>个人网页</td>  
  58.                         <td><input type="text" name="purl" /></td>  
  59.                         <td></td>  
  60.                     </tr>  
  61.                     <tr>  
  62.                         <td>电话</td>  
  63.                         <td><input type="text" name="telephone" /></td>  
  64.                         <td></td>  
  65.                     </tr>  
  66.                     <tr>  
  67.                         <td>附件</td>  
  68.                         <td><input type="file" name="afile"/></td>  
  69.                         <td></td>  
  70.                     </tr>  
  71.                     <tr><td colspan="3" ><input type="submit" name="submit" value="提交" /><button>重置</button></td></tr>  
  72.                 </tbody>             
  73.             </table>  
  74.         </form>  
  75.   </div>     
  76.   </body>  
  77. </html>  
jQuery验证框架

Js代码 复制代码  收藏代码
  1. $(function(){   
  2.     var validator = $("#myform").validate({   
  3.         debug: true,       //调试模式取消submit的默认提交功能  
  4.         errorClass: "haha",//默认为错误的样式类为:error  
  5.         focusInvalid: false,   
  6.         onkeyup: false,   
  7.         submitHandler: function(form){   //表单提交句柄,为一回调函数,带一个参数:form  
  8.             alert("提交表单");   
  9.             //form.submit();   提交表单   
  10.         },   
  11.         rules: {           //定义验证规则,其中属性名为表单的name属性  
  12.             username: {   
  13.                 required: true,   
  14.                 minlength: 2,   
  15.                 remote: "uservalid.jsp"  //传说当中的ajax验证  
  16.             },   
  17.             firstpwd: {   
  18.                 required: true,   
  19.                 //minlength: 6   
  20.                 rangelength: [6,8]   
  21.             },   
  22.             secondpwd: {   
  23.                 required: true,   
  24.                 equalTo: "#password"  
  25.             },   
  26.             sex: {   
  27.                 required: true  
  28.             },   
  29.             age: {   
  30.                 required: true,   
  31.                 range: [0,120]   
  32.             },   
  33.             email: {   
  34.                 required: true,   
  35.                 email: true  
  36.             },   
  37.             purl: {   
  38.                 required: true,   
  39.                 url: true  
  40.             },   
  41.             afile: {   
  42.                 required: true,   
  43.                 accept: "xls,doc,rar,zip"  
  44.             }   
  45.         },   
  46.         messages: {       //自定义验证消息   
  47.             username: {   
  48.                 required: "用户名是必需的!",   
  49.                 minlength: $.format("用户名至少要{0}个字符!"),   
  50.                 remote: $.format("{0}已经被占用")   
  51.             },   
  52.             firstpwd: {   
  53.                 required: "密码是必需的!",   
  54.                 rangelength: $.format("密码要在{0}-{1}个字符之间!")   
  55.             },   
  56.             secondpwd: {   
  57.                 required: "密码验证是必需的!",     
  58.                 equalTo: "密码验证需要与密码一致"  
  59.             },   
  60.             sex: {   
  61.                 required: "性别是必需的"  
  62.             },   
  63.             age: {   
  64.                 required: "年龄是必需的",   
  65.                 range: "年龄必须介于{0}-{1}之间"  
  66.             },   
  67.             email: {   
  68.                 required: "邮箱是必需的!",   
  69.                 email: "请输入正确的邮箱地址(例如 myemail@163.com)"  
  70.             },   
  71.             purl: {   
  72.                 required: "个人主页是必需的",   
  73.                 url: "请输入正确的url格式,如 http://www.domainname.com"  
  74.             },   
  75.             afile: {   
  76.                 required: "附件是必需的!",   
  77.                 accept: "只接收xls,doc,rar,zip文件"  
  78.             }   
  79.         },   
  80.         errorPlacement: function(error, element) {  //验证消息放置的地方  
  81.             error.appendTo( element.parent("td").next("td") );   
  82.         },   
  83.         highlight: function(element, errorClass) {  //针对验证的表单设置高亮  
  84.             $(element).addClass(errorClass);   
  85.         },   
  86.         success: function(label) {     
  87.                     label.addClass("valid").text("Ok!")     
  88.             }     
  89.            
  90.         /*,  
  91.         errorContainer: "#error_con",               //验证消息集中放置的容器 
  92.         errorLabelContainer: "#error_con ul",       //存放消息无序列表的容器 
  93.         wrapper: "li",                              //将验证消息用无序列表包围 
  94.         validClass: "valid",                        //通过验证的样式类 
  95.         errorElement: "em",                         //验证标签的名称,默认为:label 
  96.         success: "valid"                            //验证通过的样式类 
  97.         */  
  98.     });   
  99.     $("button").click(function(){   
  100.         validator.resetForm();   
  101.     });   
  102.     //alert($("#password").rules()["required"]);  
  103.     //validator.showErrors({"username": "用户名是必需的"});  
  104.     /*$("button").click(function () {  
  105.         var str = "Hello {0}, this is {1}";  
  106.         alert("'" + str + "'");  
  107.         str = $.validator.format(str, ["koala","oo"]); 
  108.         alert("'" + str + "'");  
  109.     });*/  
  110.                
  111. });   
[3] 远程验证程序
Java代码 复制代码  收藏代码
  1. <%@ page language="java" import="java.io.PrintWriter" pageEncoding="gb2312"%><%   
  2.     String username = request.getParameter("username");   
  3.     PrintWriter pw = response.getWriter();   
  4.     try{   
  5.         if(username.toLowerCase().equals("admin")){   
  6.             pw.println("true");   
  7.         }else{   
  8.             pw.println("false");   
  9.         }   
  10.     }catch(Exception ex){   
  11.         ex.getStackTrace();   
  12.     }finally{   
  13.         pw.flush();   
  14.         pw.close();   
  15.     }   
  16. %>  
[4] 验证效果





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值