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

MVC中如何对foreach循环生成的多行文本框实现JavaScript验证

问题根源

你用foreach循环生成每行输入框时,给所有行的手机号、邮箱输入框设置了相同的固定id(txtMobile、txtEmail)。HTML规范要求DOM元素的id必须全局唯一,使用$('#xxx')按id选择元素时,只会返回页面上第一个匹配的元素,所以只有第一行的输入能被验证逻辑命中。

代码调整方案

1. 调整视图层代码

修改输入框的onchange绑定,将当前触发事件的元素作为参数传入验证方法,同时删除重复的固定id属性(保留原有类名即可),修改后的循环部分代码如下:

@foreach (var item in Model.Directors)
{
    <tr class="item1">
        <td hidden>
            <input type="hidden" class="id1" value="@item.ID" />
        </td>
        <td>
            <input type="text" class="name1" value="@item.Dir_Name" onchange="DirectorValidation(this);" style="text-transform:uppercase">
        </td>
        <td>
            <input type="text" class="mobile1" value="@item.Dir_Mobile" onchange="DirectorValidation(this);">
        </td>
        <td>
            <input type="text" class="email1" value="@item.Dir_Email" onchange="DirectorValidation(this);" style="text-transform: uppercase">
        </td>
    </tr>         
}

2. 调整JS验证逻辑

接收传入的当前元素,先定位到元素所在的当前行,再在当前行范围内查找手机号、邮箱输入框做验证,修改后的代码如下:

function DirectorValidation(currentEl) {
  // 定位当前输入框所属的行
  const currentRow = $(currentEl).closest('tr');
  // 仅在当前行内查找对应输入框
  const $mobileInput = currentRow.find('.mobile1');
  const $emailInput = currentRow.find('.email1');

  if ($mobileInput.val() == "") {
    alert('Enter Mobile No.');
    $mobileInput.focus();
    return false;
  }

  var mobilePattern = /^([6-9]\d{9})$/;
  if (!$mobileInput.val().match(mobilePattern)) {
    alert('Invalid Mobile No.');
    $mobileInput.focus();
    return false;
  }

  if ($emailInput.val().trim() == "") {
    alert('Please Enter Email.');
    $emailInput.focus();
    return false;
  }

  var emailPattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  if (!$emailInput.val().match(emailPattern)) {
    alert('Invalid Email Id.');
    $emailInput.focus();
    return false;
  }
}

调整后任意行的输入框触发change事件,都会仅校验当前行的输入内容,所有行均可正常触发验证逻辑。

内容的提问来源于stack exchange,提问作者shubham raut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:24:03