【问题标题】:How to validate dynamic table when using ajax post使用ajax post时如何验证动态表
【发布时间】:2016-03-19 12:48:30
【问题描述】:

我正在尝试将 jQuery 验证添加到我的应用程序中的动态表中。这是我的代码。

    <table border="1px" id="table">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        <tr>
            <td><input type=text name="fname_new[0]" class="table_input" /></td>
            <td><input type=text name="lname_new[0]" class="table_input" /></td>

        </tr>
    </table>
  <input type="button" name="submit" value="Submit" id="submit" />

单击添加按钮时,我正在通过 jquery 添加行

  $("#AddLine").click(function () {
  var row = "<tr><td><input name=fname_new[" + num_rows + "] type=text class='table_input' /></td><td><input name=lname_new[" + num_rows + "]type=text class='table_input' /></td></tr>";
      $("#table").append(row);
            num_rows++;
    });

在这里,我使用 ajax post 提交表单。表单是这样提交的

<input type="button" id="savebutton" value="save'/>

点击按钮后,表单会像这样发布

 $.ajax({
            url: '@Url.Action("", "MyCOntroller")',
            type: 'POST',
            data: formdata,
            datatype: 'json',
            success: function (response) {
                $('#UserMessage').html(response.UserMsg);

            },
            error: function (error) {
            }
        });

我想使用 jQuery 验证动态表,谁能告诉我在通过 ajax 发布之前如何验证。

【问题讨论】:

  • 验证什么?文本框有值吗?它匹配一个正则表达式?

标签: jquery ajax model-view-controller


【解决方案1】:

这取决于各种各样的事情。比如你想验证什么?你用的是什么框架?

例如,如果您想验证必须输入一个值,则需要在输入中添加一个属性:data-val-required="The xxxxx field is required"。然后在调用您的 ajax 函数之前使用if ($('#yourFormId').valid()) 检查数据是否有效。您还需要一个数据验证消息显示,我目前不记得它的语法。

有很多事情可以验证,而不仅仅是一个字段是必需的。您应该查找 jQuery 验证,因为那里已经有很多很容易找到的信息。

如果您使用的是 ASP.Net MVC,那么您应该考虑不显眼的验证。然后,您可以在模型中添加数据注释,例如 [Required],并且在使用 Html.EditorFor 等时会自动添加必要的属性。同样,这很容易找到相关信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2020-04-27
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多