即时验证密码规则

时间:2011-11-08 18:08:34

标签: javascript jquery html

我有一个用户注册表,用户需要输入密码。我有一些密码规则,必须包含8个字符,数字和大写等。

如何在打字时显示用户是否符合密码标准,并在小弹出窗口或类似内容中显示?

目前我的代码只有在符合这些标准时才显示刻度线(如8个字符,1个大写字母和1个数字)

  <td>
            <table><tr>
                <td>
              <input type="password" name="password"
              size="25" tabindex="<%= get_next_tabindex(@content_data) %>"
              value="<%= @content_data['password'] %>"
              onKeyUp="validatePassword(this)">
          </td>
          <td id="password_Valid_Image" style="display:none">
            <%=  image_tag(
                "/assets/20/tick-icon.png",
                :alt => "") %>
          </td>
              </tr>
            </table>
          </td>

var is_Password_Valid = false;
var lower_Case = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var upper_Case = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var numbers = [1,2,3,4,5,6,7,8,9,0]

function validatePassword(password_Input){
  is_Password_Valid = true;

  if(password_Input.value.length < 8){
    is_Password_Valid = false;
    drawPasswordValid(is_Password_Valid);
    return;
  }

  var found_Chars = 0;

  for(var i=0; i<lower_Case.length; i++){
      if(password_Input.value.indexOf(lower_Case[i]) > -1){
        found_Chars++;
      }
  }

  if(found_Chars == 0){
    is_Password_Valid = false;
    drawPasswordValid(is_Password_Valid);
    return;
  }

  found_Chars = 0;

  for(var i=0; i<upper_Case.length; i++){
      if(password_Input.value.indexOf(upper_Case[i]) > -1){
        found_Chars++;
      }
  }

  if(found_Chars == 0){
    is_Password_Valid = false;
    drawPasswordValid(is_Password_Valid);
    return;
  }

  found_Chars = 0;

  for(var i=0; i<numbers.length; i++){
      if(password_Input.value.indexOf(numbers[i]) > -1){
        found_Chars++;
      }
  }

  if(found_Chars == 0){
    is_Password_Valid = false;
    drawPasswordValid(is_Password_Valid);
    return;
  }

  drawPasswordValid(is_Password_Valid);

  }

2 个答案:

答案 0 :(得分:3)

查看现有的jQuery插件:10 Password Strength Meter Scripts For A Better Registration Interface

function check(str) {

    var length = new RegExp('^[\\d\\w]{6,}$');
    var digit = new RegExp('[\\d]+');
    var upper = new RegExp('[A-Z]+');

    return length.test(str) && digit.test(str) && upper.test(str);

}

alert(check('asasasA77'));

代码:http://jsfiddle.net/wYDej/1/

答案 1 :(得分:1)

如果您不是在寻找力量计而只是想向用户显示一些信息,请查看jQuery气泡弹出:http://www.vegabit.com/jquery_bubble_popup_v2/