如何使用JavaScript验证动态添加的多个Items输入框?
Fixing Dynamic Items Non-Empty Validation in Your Form
The issue with your current validation code is that using return false inside the forEach loop only exits the current iteration of the loop—not the entire validateForm function. That means even if an empty item input is found, the function will still proceed to return true at the end, which defeats the purpose of validation.
Here's the corrected version of your validateForm function, with a proper fix for validating all dynamic item inputs:
function validateForm () { var amount = document.forms["salesform"]["amount"]; var buyer = document.forms["salesform"]["buyer"]; var buyerRegex = /^[a-zA-Z0-9_ ]*$/; var receipt_id = document.forms["salesform"]["receipt_id"]; var receiptIdRegex = /^[a-zA-Z_ ]*$/; var items = document.querySelectorAll(".items"); var itemsRegex = /^[a-zA-Z_ ]*$/; var buyer_email = document.forms["salesform"]["buyer_email"]; var note = document.forms["salesform"]["note"]; var city = document.forms["salesform"]["city"]; var phone = document.forms["salesform"]["phone"]; var entry_by = document.forms["salesform"]["entry_by"]; if (amount.value == "") { alert("Please enter the amount."); amount.focus(); return false; } else if (isNaN(amount.value)) { alert("Amount should be only numeric value."); amount.focus(); return false; } if (buyer.value == "") { alert("Buyer name is required"); buyer.focus(); return false; } else if (!buyerRegex.test(buyer.value)) { alert("Buyer name only contain letter, number and space."); buyer.focus(); return false; } else if (buyer.value.length > 20 ) { alert("Buyer name must be less than 20 characters long."); buyer.focus(); return false; } if (receipt_id.value == "") { alert("Receipt Id is required"); receipt_id.focus(); return false; } else if (!receiptIdRegex.test(receipt_id.value)) { alert("Receipt Id must contain only characters."); receipt_id.focus(); return false; } // Fixed validation for all dynamic items for (let i = 0; i < items.length; i++) { const currentItem = items[i]; // Use trim() to catch inputs with only whitespace if (currentItem.value.trim() === "") { alert("Item name is required"); currentItem.focus(); return false; // This exits the entire validateForm function immediately } // Optional: Uncomment below to add regex validation for items // if (!itemsRegex.test(currentItem.value)) { // alert("Item name can only contain letters, underscores and spaces."); // currentItem.focus(); // return false; // } } return true; }
Key Changes Explained:
- Swapped
forEachfor a traditionalforloop: UnlikeforEach, aforloop lets us usereturn falseto immediately exit the entire validation function when an empty input is found—this stops the form from submitting right away. - Added
trim()check: This ensures inputs filled only with whitespace are treated as empty, covering a common edge case you might have missed. - Optional regex validation: I included a commented-out section to apply your
itemsRegexto each item input, in case you want to extend validation beyond just non-empty checks.
Alternative Modern Approach (Using Array Methods):
If you prefer more modern JavaScript, you can use array methods to achieve the same result:
// Check for any empty item const hasEmptyItem = Array.from(items).some(item => item.value.trim() === ""); if (hasEmptyItem) { // Find the first empty item to focus on const emptyItem = Array.from(items).find(item => item.value.trim() === ""); alert("Item name is required"); emptyItem.focus(); return false; }
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

