我想限制用户输入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>
答案 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}$
以下是一个完整的例子:
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