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

جواب «Step 2: Validate» چالش 2 از جلسه‌ی 48

سؤال

حالا اعتبارسنجی اضافه کن. در post، قبل از ساختن پیام: اگر نام یا پیام (بعد از trim) خالی است، چیزی اضافه نکن و #status را empty کن؛ اگر پیام بلندتر از ۲۰ حرف است، اضافه نکن و #status را too long کن؛ وگرنه پیام را مثل قبل بساز و #status را posted کن.

راهنما

دو if با return در ابتدای تابع. msg.length > 20.

یک جواب درست

<h2>Guestbook</h2>
<input id="name" placeholder="name">
<input id="msg" placeholder="message">
<button id="send" onclick="post()">Send</button>
<p id="status">-</p>
<ul id="list"></ul>

<script>
function post() {
  const name = document.getElementById("name").value;
  const msg = document.getElementById("msg").value;
  const status = document.getElementById("status");
  const list = document.getElementById("list");
  if (name.trim() === "" || msg.trim() === "") {
    status.textContent = "empty";
    return;
  }
  if (msg.length > 20) {
    status.textContent = "too long";
    return;
  }
  const li = document.createElement("li");
  const who = document.createElement("b");
  who.textContent = name + ": ";
  const what = document.createElement("span");
  what.textContent = msg;
  li.appendChild(who);
  li.appendChild(what);
  list.appendChild(li);
  status.textContent = "posted";
}
</script>

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