You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

注册表单用户名唯一性验证功能实现求助(附代码)

Fixing Your Username Registration Form

Let's get your username registration functionality working as intended. I'll break down the issues in your current code and provide a corrected version with clear explanations.

Issues in Your Current Code

  • Invalid duplicate check logic: Your userName function uses data["uName"] !== data["uName"] which is always false (a value can't not equal itself). Worse, data is an array of objects, not a single object with a uName property—this check doesn't actually look through existing users at all.
  • No pre-add validation: The addData function pushes new users directly into the array without first verifying if the username already exists.
  • Redundant event bindings: You added onsubmit handlers to the form, input field, and submit button—this is unnecessary and can cause unexpected behavior. Only the form needs an onsubmit handler.
  • Misplaced validation trigger: The input field's onsubmit event will never fire; form validation should happen when the user submits the form, not on the input itself.

Corrected Code

HTML

<div id="format">
  <form id="myForm" onsubmit="myFormData(event);">
    <b>User Name:</b><br>
    <input type="text" name="uName" id="uName" required="required"><br>
    <button type="submit" name="submit" id="submit">Submit</button>
  </form>
  <div id="sample"></div>
</div>

JavaScript

"use strict";
var data = [];

function myFormData(event) {
  event.preventDefault(); // Prevent default form submission behavior
  var uName = document.getElementById("uName").value.trim(); // Trim whitespace to avoid invalid entries

  // Check if username already exists
  if (isUsernameExists(uName)) {
    alert("Username is already existing");
    return; // Exit function if duplicate is found
  }

  // If username is new, add to array and confirm success
  var userObject = { uName: uName };
  addData(userObject);
  alert("Username Is Now Registered");
  document.getElementById("uName").value = ""; // Clear input field after successful registration
  console.log(data);
}

function isUsernameExists(username) {
  // Use Array.some() to check for matching usernames (case-insensitive)
  return data.some(user => user.uName.toLowerCase() === username.toLowerCase());
}

function addData(userObject) {
  data.push(userObject);
  redrawList();
}

function removeData(event) {
  var index = this.getAttribute("data-index");
  data.splice(index, 1);
  redrawList();
  console.log(data);
}

function redrawList() {
  var container = document.getElementById("sample");
  container.innerHTML = ""; // Reset displayed list

  for (var index = 0; index < data.length; index++) {
    var theDiv = document.createElement("div");
    var userObject = data[index];
    var divHTML = `uName: ${userObject.uName}<br>`;
    
    var button = document.createElement("button");
    button.type = "button";
    button.setAttribute("data-index", index);
    button.innerHTML = "X";
    button.onclick = removeData;

    theDiv.innerHTML = divHTML;
    theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
    theDiv.appendChild(button);
    container.appendChild(theDiv);
  }
}

Key Fixes Explained

  1. Proper duplicate check: The new isUsernameExists function uses Array.some() to iterate through the data array and check for matching usernames (case-insensitive for better user experience).
  2. Validation before addition: In myFormData, we first verify if the username exists. If it does, we show an error alert and stop execution. Only new usernames get added to the array.
  3. Cleaned up event bindings: Removed redundant onsubmit handlers from the input and button—only the form retains the handler to manage submission logic.
  4. Quality of life improvements: Added trim() to the input value to avoid accidental whitespace-only entries, and clear the input field after successful registration.
  5. Simplified redraw logic: Removed unnecessary loops over object properties (since we only track uName) for cleaner, more efficient code.

内容的提问来源于stack exchange,提问作者Mavis Zero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:21:41