如何在 Javascript 中比较密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21818315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:45:03  来源:igfitidea点击:

How to compare passwords in Javascript

javascript

提问by user2110655

I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database. I cannot seem to get it to work. Any ideas?

我有一个注册页面,我想在将它写入 websql 数据库之前比较两个密码(输入字段)是否相等。我似乎无法让它工作。有任何想法吗?

function addTodo() {
var todo = document.getElementById("todo");
  var todo2 = document.getElementById("todo2");

  if(todo != todo2) {
    alert("Yours passwords do not match");
  } else {
    curatio.webdb.addTodo(todo.value);
    todo.value = "";
    alert("Your Registration was successfull");
    setTimeout(function () {
    window.location.href = "login.html"; 
    }, 1000);
}
}


<div data-role="fieldcontain" >
            <label for="todo">
                &nbsp;Password
            </label>
            <input name="" id="todo" placeholder="" value="" type="password" required>
            </div>


            <div data-role="fieldcontain" >
            <label for="todo2">
                &nbsp;Retype your Password
            </label>
            <input name="" id="todo2" placeholder="" value="" type="password" required>
            </div>

回答by Marty

You're comparing the elements instead of their values.

您正在比较元素而不是它们的值。

var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");

if(todo != todo2) { // Oops

todoand todo2are 2 different<input>elements.

todo并且todo2是 2 个不同的<input>元素。

Try using .value:

尝试使用.value

if(todo.value !== todo2.value) {

回答by Cilan

You're comparing the actual elements, which will always be true(because they are both TextFields). Compair their values, like so:

您正在比较实际元素,这将始终是true(因为它们都是 TextFields)。比较它们的值,如下所示:

var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;

Either this or change

要么这个要么改变

if(todo != todo2)

to

if(todo.value != todo2.value)