在表中设置动态文本框的类验证

时间:2015-04-24 02:10:45

标签: jquery css asp.net-mvc validation

我有一个包含一行动态文本框的表。示例如下:

enter image description here

我在表格中添加了一行,点击[+]添加新目标,它将出现在屏幕下方:

enter image description here

我想将验证类添加到表格内的所有文本框中。因此,当用户单击“保存”按钮时,它将检查所有文本框。

我尝试将此jquery用于此:

exec doesn't support the nested "for" element.

我正在使用MVC 5,jquery-1.10.2.js,jquery-1.10.2.min.js,jquery.validate *&具有类 input.input-validation-error

的Site.css

在我的模特中:

 $('#tbTargetDetails tr').each(function () {
            $(this).find('td input:text').each(function (i,a) {
                // get each of the textbox and add validation class to it
            });
        });

我在另一个模型中调用上面的模型:

 public class ClsTargetInfo
    {
        public string ItemNumber_Target { get; set; }
        [Required]
        public string TargetColor_U { get; set; }
        [Required]
        public string TargetColor_V { get; set; }
        [Required]
        public string D90Target_U { get; set; }
        [Required]
        public string D90Target_V { get; set; }
        [Required]
        public string D10Target_U { get; set; }
        [Required]
        public string D10Target_V { get; set; }
        [Required]
        public string Thickness { get; set; }
        [Required]
        public string FilmWidth { get; set; }
        [Required]
        public string TargetDate { get; set; }
    }

以下是添加新行时的代码:

public class abc
{
 public IList<ClsTargetInfo> TargetInfo { get; set; }
}

请帮助解决我的问题。非常感谢你的帮助。 谢谢。

2 个答案:

答案 0 :(得分:8)

您没有在文本框中包含必要的data-val属性,也没有用于显示验证消息的占位符元素,jquery.validate.unobtrusive.js用它来进行客户端验证。此外,您当前的实现不允许用户通过包含索引器的隐藏输入来删除可以解决的最后一行的其他任何内容,这允许非连续索引器被发布并绑定到您的集合。

首先向您的ClsTargetInfo属性添加一个默认TargetInfo对象,然后在视图中生成其html

<table id="table"> // add an id attribute
  <thead>.....</thead>
  <tbody is="tablebody"> // add an id attribute
    for(int i = 0; i < Model.TargetInfo.Count; i++)
    {
      <tr>
        <td>
          @Html.TextBoxFor(m => m.TargetInfo[i].TargetColor_U, new { id="", @class="form-control" }) // remove the unnecessary id attribute
          @Html.ValidationMessageFor(m => m.TargetInfo[i].TargetColor_U)
          // Add the following hidden input to only one column in the row
          <input type="hidden" name="TargetInfo.Index" value=@i />
        </td>
        <td>
          @Html.TextBoxFor(m => m.TargetInfo[i].TargetColor_V, new { id="", @class="form-control" }) // remove the unnecessary id attribute
          @Html.ValidationMessageFor(m => m.TargetInfo[i].TargetColor_V)
        </td>
        .... // other columns
      </tr>
    }
  </tbody>
</table>

然后检查它为<tr>元素生成的html,它应该看起来像

<tr>
  <td>
    <input data-val="true" data-val-required="The TargetColor_U field is required" name="TargetInfo[0].TargetColor_U" type="text" value="">
    <span class="field-validation-valid errorText" data-valmsg-for="TargetInfo[i].TargetColor_U" data-valmsg-replace="true"></span>
    <input type="hidden" name="TargetInfo.Index" value="0" />
  </td>
  ....
</tr>

并将其复制到隐藏的元素中,该元素放置在外部表单标记中,并将所有索引器实例替换为虚拟字符,以便name="TargetInfo[0].TargetColor_U"变为name="TargetInfo[#].TargetColor_U"),并且还会替换隐藏输入的value属性,以便value="0"变为value="#"

<table id="newrow" style="display:none">
  .... // copy the tr element and its contents here
</table>

然后脚本看起来像

var form = $('form'); // or use the id if you have given the form an id
var newrow= $('#newrow');
var tablebody = $('#tablebody'); // modify to suit your id
$("#btnAddTarget").click(function() {
  var index = (new Date()).getTime(); // unique indexer
  var clone = newrow.clone(); // clone the new row
  clone.html($(clone).html().replace(/#/g, index)); // update the indexer of the clone
  var row = clone.find('tr');
  tablebody.append(row); // add the new row to the table
  // Reparse the validator
  form.data('validator', null);
  $.validator.unobtrusive.parse(form);
});

附注:

  1. 通过解析data-val属性进行不显眼的验证 首次呈现表单时。添加动态内容时,它是 必须重新解析验证器,如最后两行所示 剧本。
  2. 为索引器添加隐藏输入允许您 删除集合中的任何行,因此删除“删除”按钮是 不再需要,将为用户提供更好的体验。
  3. 而是使用内联样式,例如,使用css而不是<td style="padding-left:0px;padding-top:0px;padding-bottom:0px;padding-right:0px">,您应该在#table td { padding: 0; }文件中使用.css
  4. 虽然添加纯粹的客户端行提供了最佳性能, 它很难维护。如果您添加或更改任何验证 属性上的属性(例如,您稍后可能会添加一个 [StringLength]属性),您需要将html更新为 适合。作为替代方案,您可以考虑使用 BeginCollectionItem帮助器,这意味着你有一个部分 view(表示一行表)。对于现有项目,您使用a foreach循环@Html.Partial(),对于新行,您使用ajax 调用返回局部视图的控制器方法,和 更新DOM

答案 1 :(得分:0)

<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        function DeleteRow(btn) {

            //alert("delete" + btn);
            var tr = btn.closest('tr');
            tr.remove();
        }
        $(".btnsd").click(function () {
            // debugger;
            alert("hjkghk");
            divs = $('.val')
            for (ind in divs) {
                var div = divs[ind];
                if (div.value == "") {
                    div.focus();
                    return false;
                }
            }
            $('#Employertbl').append(
                                    '<tr>' +
                                        '<td> @Html.TextBox("item.employer_name", null, new { @class = "form-control val" })</td>' +
                                        '<td width="24%"> <div style="float:left; padding-right:5px;">@Html.TextBox("item.duration_From", null, new { @id = "", @placeholder = "From Date", @class = "form-control input-date datepicker val", @readonly = true })</div> ' +
                                              '<div>@Html.TextBox("item.duration_to", null, new { @id = "", @class = "form-control input-date datepicker val", @placeholder = "To Date", @readonly = true })</div></td>' +
                                        '<td> @Html.TextBox("item.designation", null, new { @class = "form-control val" })</td>' +
                                        '<td> @Html.TextBox("item.worked_skill", null, new { @class = "form-control val" })</td>' +
                                        '<td> @Html.TextBox("item.proj_handled", null, new { @class = "form-control val" })</td>' +
                                        '<td>  @Html.CheckBox("item.current_employed",new{@class = "current" })</td>' +
                                        '<td><input type="button" value="Remove" onclick="DeleteRow(this)" name="delete" class="btn blue pull-right" /> </td>' +
                                    '</tr>'
                                    );



        });
    });
</script>


<div class="table-responsive">
    <table id="Employertbl" class="table table-striped table-bordered table-hover dataTable no-footer">
        <tbody>
            <tr>
                <th>Employer Name</th>
                <th>Duration</th>
                <th>Designation</th>
                <th>Worked skill(s)</th>
                <th>Reason of change</th>
                <th>Currently Employed</th>
                <th>Action</th>
            </tr>

            <tr>
                <td>
                    <input class="form-control val" id="item_employer_name" name="item.employer_name" type="text" value="">
                </td>
                <td width="24%">
                    <div style="float:left; padding-right:5px;"><input class="form-control input-date datepicker val hasDatepicker" name="item.duration_From" placeholder="From Date"  type="text" value="" id="dp1459328857835"></div>
                    <div> <input class="form-control input-date datepicker val hasDatepicker" name="item.duration_to" placeholder="To Date"  type="text" value="" id="dp1459328857836"></div>

                </td>
                <td>
                    <input class="form-control val" id="item_designation" name="item.designation" type="text" value="">
                </td>
                <td>
                    <input class="form-control val" id="item_worked_skill" name="item.worked_skill" type="text" value="">
                </td>
                <td>
                    <input class="form-control val" id="item_proj_handled" name="item.proj_handled" type="text" value="">
                </td>
                <td>
                    <input class="current" id="item_current_employed" name="item.current_employed" type="checkbox" value="true"><input name="item.current_employed" type="hidden" value="false">
                </td>
                <td>
                    <input id="myButton" type="button" value="add"  name="delete" class="btnsd bcbn">
                </td>
            </tr>


            <tr><td> <input class="form-control val" id="item_employer_name" name="item.employer_name" type="text" value=""></td><td width="24%"> <div style="float:left; padding-right:5px;"><input class="form-control input-date datepicker val hasDatepicker" name="item.duration_From" placeholder="From Date"  type="text" value="" id="dp1459328857837"></div> <div><input class="form-control input-date datepicker val hasDatepicker" name="item.duration_to" placeholder="To Date" type="text" value="" id="dp1459328857838"></div></td><td> <input class="form-control val" id="item_designation" name="item.designation" type="text" value=""></td><td> <input class="form-control val" id="item_worked_skill" name="item.worked_skill" type="text" value=""></td><td> <input class="form-control val" id="item_proj_handled" name="item.proj_handled" type="text" value=""></td><td>  <input class="current" id="item_current_employed" name="item.current_employed" type="checkbox" value="true"><input name="item.current_employed" type="hidden" value="false"></td><td><input type="button" id="myButton" value="add" name="delete" class="btnsd dfsd"> </td></tr>
            <tr><td> <input class="form-control val" id="item_employer_name" name="item.employer_name" type="text" value=""></td><td width="24%"> <div style="float:left; padding-right:5px;"><input class="form-control input-date datepicker val hasDatepicker" name="item.duration_From" placeholder="From Date" type="text" value="" id="dp1459328857839"></div> <div><input class="form-control input-date datepicker val hasDatepicker" name="item.duration_to" placeholder="To Date"  type="text" value="" id="dp1459328857840"></div></td><td> <input class="form-control val" id="item_designation" name="item.designation" type="text" value=""></td><td> <input class="form-control val" id="item_worked_skill" name="item.worked_skill" type="text" value=""></td><td> <input class="form-control val" id="item_proj_handled" name="item.proj_handled" type="text" value=""></td><td>  <input class="current" id="item_current_employed" name="item.current_employed" type="checkbox" value="true"><input name="item.current_employed" type="hidden" value="false"></td><td><input type="button" id="myButton" value="add" name="delete" class="btnsd"> </td></tr>
        </tbody>
    </table>
</div>
相关问题