javascript中的length属性无法正常工作

时间:2013-02-15 07:30:33

标签: javascript html5

我想限制用户输入6-20个字符的密码。但是下面的功能不能正常工作。

 function validatePass(pwd1, pwd2)
 {
var len = document.getElementById('pwd1').value;
if(len.length < 6 || len.length > 20)
{ pwd1.setCustomValidity('Enter 6-20 characters');
}
else if (pwd1.value != pwd2.value || pwd1.value == '' || pwd2.value == '' )
{
        pwd2.setCustomValidity('Password incorrect');
  } 
else 
{
    pwd2.setCustomValidity('');
}
}

html代码是:

<h4>Password</h4></td>
<td><input type="password" name="pwd1" size="30" id="pwd1" required placeholder="Enter 6-20 characters"></td></tr>
<tr><td>
<h4>Confirm Password</h4></td>
<td><input type="password" name="pwd2" id="pwd2" size="30" required onfocus="validatePass(document.getElementById('pwd1'), this);" oninput="validatePass(document.getElementById('pwd1'), this);">
</td></tr>

2 个答案:

答案 0 :(得分:1)

在HTML5中,您可以使用pattern属性:

<input type="password" pattern=".{6,20}" name="pwd1" size="30" id="pwd1" required placeholder="Enter 6-20 characters"></td></tr>

答案 1 :(得分:0)

尝试使用这样的正则表达式:

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{6,20}$

来源:.NET RegEx to validate password between 6 and 20 characters with at least one upper case letter, one lower case letter and one digit

以下是一个完整的例子:

function CheckPassword(inputtxt) 
{ 
var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
if(inputtxt.value.match(passw)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
}

来源:http://www.w3resource.com/javascript/form/password-validation.php