簡體   English   中英

創建登錄時出現問題

[英]Trouble with creating a login

我試圖確保我們的用戶名中包含一個數字,我們的密碼是 012345678。這是否正確? 我的 HTML 中有一個包含電子郵件、用戶名和密碼的表格。

document.getElementById("login").addEventListener("submit", function(event) {
  event.preventDefault();

  var user = document.querySelector(" input[name=username]");
  var pass = document.querySelector(" input[name=password]");

  if (user.value.includes(0) ||
    user.value.includes(1) ||
    user.value.includes(2) ||
    user.value.includes(3) ||
    user.value.includes(4) ||
    user.value.includes(5) ||
    user.value.includes(6) ||
    user.value.includes(7) ||
    user.value.includes(8) ||
    user.value.includes(9)) {
    // user is good
    //now.. check the password
  } else {
    alert("Incorrect");
  }

  if (pass == 012345678) {
  } else {
    alert("Incorrect");
  }

  var Hmmm = document.getElementsByClassName("h1")[1]; {
    document.querySelector("h1").innerText = "Good Job"
  }    
});

不完全正確,不。

您的“pass”和“user”變量將保存字符串。 所以你需要對它們使用字符串函數,並將它們與字符串進行比較。

這意味着您不能使用“includes”,因為它不是有效的字符串函數 相反,你會使用

user.value.indexOf("0")>=0 // indexOf will return -1 if it can't find what you are looking for

話雖如此,有一種更好的方法可以使用正則表達式來測試字符串是否至少包含一位數字:

user.value.match(/[0-9]/)

最后,正如我所說,您需要將字符串與字符串進行比較。 因此,對於您的密碼檢查:

pass.value === "012345678"

我使用了嚴格相等運算符 (===),因為在這種情況下,您絕對希望值是這個完整的字符串。 當您使用普通的相等運算符 (==) 時,有時可能會發生一些轉換並產生誤報。

希望這可以幫助!

我建議使用正則表達式

 window.onload = function() { document.getElementById('test').onclick = function() { // test username var uname = document.getElementById('username').value; // test password var password = document.getElementById('password').value; if (checkUsername(uname) && checkPassword(password)) { console.log('everything is good!'); } else { console.log('something is wrong'); } } } function checkUsername(uname) { // checks if the username contains a digit with regex if (/\\d/.test(uname)) { console.log('Username contains digit'); return true; } else { console.log('Username needs to have a digit in it.'); return false; } } function checkPassword(password) { // checks the password to be equal to string constant if (password === '012345678') { console.log('good password'); return true; } else { console.log('bad password'); return false; } }
 <label for="username">Username: <input type="textbox" id="username" /></label> <label for="password">Password: <input type="password" id="password" /></label> <input type="button" id="test" value="Submit" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM