注册表单用户名唯一性验证功能实现求助(附代码)
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
userNamefunction usesdata["uName"] !== data["uName"]which is alwaysfalse(a value can't not equal itself). Worse,datais an array of objects, not a single object with auNameproperty—this check doesn't actually look through existing users at all. - No pre-add validation: The
addDatafunction pushes new users directly into the array without first verifying if the username already exists. - Redundant event bindings: You added
onsubmithandlers to the form, input field, and submit button—this is unnecessary and can cause unexpected behavior. Only the form needs anonsubmithandler. - Misplaced validation trigger: The input field's
onsubmitevent 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
- Proper duplicate check: The new
isUsernameExistsfunction usesArray.some()to iterate through thedataarray and check for matching usernames (case-insensitive for better user experience). - 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. - Cleaned up event bindings: Removed redundant
onsubmithandlers from the input and button—only the form retains the handler to manage submission logic. - Quality of life improvements: Added
trim()to the input value to avoid accidental whitespace-only entries, and clear the input field after successful registration. - Simplified redraw logic: Removed unnecessary loops over object properties (since we only track
uName) for cleaner, more efficient code.
内容的提问来源于stack exchange,提问作者Mavis Zero
相关产品推荐
相关产品推荐

