我有一个工作代码来验证两个密码,但我需要添加最少量的字符
这是一个较大项目的一小部分,但对于html我有:
<input id="username" type="text" name="username" placeholder="username" size="30">
<label for="pass1">Password:</label>
<input type="password" placeholder="password" name="pass1" id="pass1">
<label for="pass2">Confirm Password:</label>
<input type="password" name="pass2" id="pass2" placeholder="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
至于我的代码
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
}
如何正确地将表达式(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)
添加到我的代码中才能正确执行?
答案 0 :(得分:1)
在检查密码是否匹配之前,请检查pass1
:
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
// check length of pass1 here
if(pass1.value.length < 8) {
message.innerHTML = "Password must be at least 8 characters.";
return;
}
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
}
答案 1 :(得分:0)
如果你想使用正则表达式,你可以这样做:
if(pass1.value == pass2.value){
var reg = /^[0-9a-zA-Z]{8,}$/;
var res = pass1.value.match(reg);
if (res == pass1.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}
else {
message.innerHTML = "Password must be at least 8 letters & numbers only."
}
}
如果正则表达式正在执行比长度检查更有趣的事情,这可能很有用,例如确认密码仅包含某些字符。上面的代码使用match()
方法来查看密码值是否与正则表达式匹配。如果是,则结果将是密码。如果没有,结果将为空。