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

如何使用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:

  1. Swapped forEach for a traditional for loop: Unlike forEach, a for loop lets us use return false to immediately exit the entire validation function when an empty input is found—this stops the form from submitting right away.
  2. Added trim() check: This ensures inputs filled only with whitespace are treated as empty, covering a common edge case you might have missed.
  3. Optional regex validation: I included a commented-out section to apply your itemsRegex to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:30:23