بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 3: Validation and Login» چالش 3 از جلسه‌ی 60

سؤال

اشکال‌های ۳ و ۴. در post: اگر پیام (بعد از trim) خالی یا بلندتر از ۳۰ حرف است، چیزی اضافه نکن و #status را invalid message کن؛ وگرنه اضافه کن و #status → posted. در login: پیام خطا برای هر حالت غلط فقط wrong username or password؛ و بعد از ۳ تلاش غلط برای یک نام، حتی رمز درست هم account locked بگیرد (کاربران: sara/tiger22). ورود درست → welcome, <name>.

راهنما

جلسه‌های ۴۸ و ۵۲ را به یاد بیاور: failed[name] = (failed[name] || 0) + 1.

یک جواب درست

<h3>Class messenger</h3>
<input id="name" placeholder="name">
<input id="pw" type="password" placeholder="password">
<button id="go" onclick="login()">Log in</button>
<p id="auth">-</p>
<input id="msg" placeholder="message">
<button id="send" onclick="post()">Post</button>
<p id="status">-</p>
<ul id="list"></ul>

<script>
const USERS = { sara: "tiger22" };
const failed = {};
function login() {
  const name = document.getElementById("name").value;
  const pw = document.getElementById("pw").value;
  const auth = document.getElementById("auth");
  if ((failed[name] || 0) >= 3) { auth.textContent = "account locked"; return; }
  if (!(name in USERS) || USERS[name] !== pw) {
    failed[name] = (failed[name] || 0) + 1;
    auth.textContent = "wrong username or password";
    return;
  }
  failed[name] = 0;
  auth.textContent = "welcome, " + name;
}
function post() {
  const name = document.getElementById("name").value;
  const msg = document.getElementById("msg").value;
  const status = document.getElementById("status");
  if (msg.trim() === "" || msg.length > 30) { status.textContent = "invalid message"; return; }
  const li = document.createElement("li");
  li.textContent = name + ": " + msg;
  document.getElementById("list").appendChild(li);
  status.textContent = "posted";
}
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن