【问题标题】:Validate re-enter of password javascript code require correction验证重新输入密码 javascript 代码需要更正
【发布时间】:2018-04-11 21:31:34
【问题描述】:

我有这个代码来验证两个字段上的数据(密码)是否相等。

当我在第一个字段中输入密码并转到第二个字段重新输入密码时,我当时收到错误交叉(fa-close)。

相反,在我离开第二个字段后,我需要它,然后我收到错误消息。

HTML:

<input type="password" name="password" id="password" /><br>
<input type="password" name="password2" id="password2" onKeyUp="checkPass(); return false;" />
<span id="confirmMessage" class="confirmMessage"></span>

这是我的 javascript 代码:

<script type="text/javascript">
function checkPass() {
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('password2');
var message = document.getElementById('confirmMessage');

var goodColor = "#fff";
var goodColored = "#087a08";
var badColor = "#fff";
var badColored = "#ed0b0b";

if(password.value == password2.value) {
  password2.style.backgroundColor = goodColor;
  message.style.color = goodColored;
  message.innerHTML = "<i class='fa fa-check'></i>"
}
else {
  password2.style.backgroundColor = badColor;
  message.style.color = badColored;
  message.innerHTML = "<i class='fa fa-close'></i>"
}
}  
</script>

我们将不胜感激。谢谢。

【问题讨论】:

  • 我们还需要您的 html 来查看问题所在。 (这可能是您调用函数的位置/附加事件的位置)
  • 编辑了@Imme的问题

标签: javascript html


【解决方案1】:

function checkPass() {
	
var get_elem = document.getElementById,
pass1 = document.getElementById('password'),
pass2 = document.getElementById('password2'),
message = document.getElementById('confirmMessage'),
colors = {
goodColor: "#fff",
goodColored: "#087a08",
badColor: "#fff",
badColored:"#ed0b0b"
},
strings = {
"confirmMessage": ["good", "bad"]
};

if(password.value === password2.value && (password.value + password2.value) !== "") {
password2.style.backgroundColor = colors["goodColor"];
message.style.color = colors["goodColored"];
message.innerHTML = strings["confirmMessage"][0];
}
else if(!(password2.value === "")) {
password2.style.backgroundColor = colors["badColor"];
message.style.color = colors["badColored"];
message.innerHTML = strings["confirmMessage"][1];
}
else {
message.innerHTML = "";	
}

}  
<input type="password" name="password" id="password" onkeyup="checkPass()" /><br>
<input type="password" name="password2" id="password2" onkeyup="checkPass()" />
<span id="confirmMessage" class="confirmMessage"></span>

此代码如何为您工作?我们调用checkValue() 每当用户释放一个键来处理用户在第二个字段然后在第一个字段中键入某些内容的情况(否则即使用户键入相同的内容,在这种情况下您也会有“错误”这两个领域的事情)。除了那个修改,我没有做太多。

编辑:我不会为元素的 id 和 class 属性使用相同的名称 (confirmMessage),请参阅 this

【讨论】:

  • 好一个。谢谢先生。
【解决方案2】:

将 checkPass() 调用放在第二个密码的 onblur 而不是第一个密码上,或者不检查第二个密码是否为空。

【讨论】:

  • @FelipeValdes 您也应该处理我在回答中描述的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
相关资源
最近更新 更多