不使用正则表达式进行表单密码验证

时间:2016-01-17 09:54:10

标签: javascript

我试图在不使用正则表达式的情况下进行密码验证,所以只有javascript没有模式或正则表达式。格式必须包含1个大写字母,1个小写字母,1个数字和1个特殊字符。因此格式必须如下:

aaaa111 - >格式无效

AaAa111 - >格式无效

A @ Ba213 - >有效格式

编辑:我很抱歉我不知道正则表达式包括在javascript ..我尝试这个验证,但没有工作

    var hasBigLetter   = false;
    var hasSmallLetter = false;
    var hasNumber      = false;
    var hasSpecialCaseLetter      = false;
    for (var i = 0; i < pass.length; i++) {
      var charCode = pass.charCodeAt(i);
      if(charCode > 47 && charCode < 58)
        hasNumber = true;
      if(charCode > 64 && charCode < 91)
        hasBigLetter = true;
      if(charCode > 96 && charCode < 123)
        hasSmallLetter = true;
      if(charCode > 32 && charCode < 48)
        hasSpecialCaseLetter   = true;


    }
if(pass == hasBigLetter && hasSmallLetter && hasNumber && hasSpecialCaseLetter)
    {
        alert("incorrect password pattern");
    }

HTML:

    <label> 
        Password : 
            <div>
             <input type="password" placeholder="Input Password" id="pass" name="pass" >
            </div>
    </label>
<input type="button" value="Submit" id="submit" onClick="validate()"> 
    </form>

1 个答案:

答案 0 :(得分:-1)

正如您现在接受使用RegEx,我根据此帖https://stackoverflow.com/a/16707675/4339170调整了解决方案:

JPanel
function validate() {
  var p = document.getElementById('pass').value
  var errors = []

  //if (p.length < 8) {
  //  errors.push("Your password must be at least 8 characters")
  //}
  if (p.search(/[a-z]/) < 0) {
    errors.push("Your password must contain at least one lowercase letter.")
  }
  if (p.search(/[A-Z]/) < 0) {
    errors.push("Your password must contain at least one uppercase letter.")
  }
  if (p.search(/[0-9]/) < 0) {
    errors.push("Your password must contain at least one digit.")
  }
  if(p.search(/[\!\@\#\$\%\^\&\*\(\)\_\+\.\,\;\:\-]/) < 0) {
    errors.push("Your password must contain at least one special character.")
  }
    
  if (errors.length > 0) {
    document.getElementById("errors").innerHTML = errors.join("<br>")
    return false;
  }
  return true;
}