使用内联编辑将Jquery验证添加到Jquery数据表

时间:2014-06-19 08:41:27

标签: jquery jquery-validate datatables

我有一个带有Jquery Datatable的MVC应用程序。

表格如下:

<div class="widget-body no-padding">
    <table id="datatable_tabletools" class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Fornavn</th>
                    <th>Etternavn</th>
                    <th>Telefon</th>
                    <th>Epost</th>
                    <th>Fylke</th>
                    <th>Handlinger</th>
                </tr>
            </thead>
            <tbody>

                @foreach (var person in Model)
                {
            <tr>
                <td><label id="Alert_Person_ID">@person.Alert_Person_ID</label></td>
                <td>
                    <span class="display-mode">
                        <label id="lblFirstName">@person.FirstName</label>
                    </span>
                    <input type="text" id="FirstName" value="@person.FirstName" class="edit-mode" />
                </td>
                <td>
                    <span class="display-mode">
                        <label id="lblLastName">@person.LastName</label>
                    </span>
                    <input type="text" id="LastName" value="@person.LastName" class="edit-mode" />
                </td>
                <td>
                    <span class="display-mode">
                        <label id="lblPhonePrimary">@person.PhonePrimary</label>
                    </span>
                    <input type="text" id="PhonePrimary" value="@person.PhonePrimary" class="edit-mode" />
                </td>
                <td>
                    <span class="display-mode">
                        <label id="lblEmailPrimary">@person.EmailPrimary</label>
                    </span>
                    <input type="text" id="EmailPrimary" value="@person.EmailPrimary" class="edit-mode" />
                </td>
                <td width="100px">
                    <span class="display-mode">
                        <label id="lblCounty">@person.County</label>
                    </span>
                    <input type="text" id="County" value="@person.County" class="edit-mode" />
                </td>
                <td width="100">
                    <button class="more-details display-mode btn btn-xs btn-default"><i class="fa fa-search"></i></button>
                    <button class="edit-user display-mode btn btn-xs btn-default"><i class="fa fa-pencil"></i></button>
                    <button class="delete-user display-mode btn btn-xs btn-default"><i class="fa fa-trash-o"></i></button>
                    <button class="save-user edit-mode btn btn-xs btn-default"><i class="fa fa-save"></i></button>
                    <button class="cancel-user edit-mode btn btn-xs btn-default"><i class="fa fa-times"></i></button>
            </tr>
                }
            </tbody>
        </table>
</div>

我有很多不同的JS方法来添加新的,更新和删除函数来添加数据。 Datatables脚本如下所示:

$('#datatable_tabletools').dataTable({

                //datatable_tabletools_filter
                // Tabletools options: 
                //   https://datatables.net/extensions/tabletools/button_options
                "sDom": "<'dt-toolbar'<'col-xs-6'f><'col-xs-6'T>r>t<'dt-toolbar-footer'<'col-xs-6'i><'col-xs-6'p>>",
                "fnDrawCallback": function () {
                    if (newrow == false) {
                        $('.edit-mode').hide();
                    }
                },
                "oTableTools": {

                    "aButtons": [
                        {
                            "sExtends": "collection",
                            "sButtonText": "Eksporter <span class=\"caret\" />",
                            "aButtons": ["copy","csv", "xls", "pdf", "print"]
                        }
                    ],
                    "sSwfPath": "../../Scripts/plugin/datatables/swf/copy_csv_xls_pdf.swf"
                }
            });

所以问题是我如何为此添加Jquery验证?

F.ex我有一个按钮来添加我追加到工具栏的新行。

 $("#datatable_tabletools_filter").prepend("<button id='new_p' class='btn btn-default' style='float:left;margin-right:10px;'><i class='fa fa-plus'></i> Ny Person</button>");

这会调用此方法将数据字段添加到表中:

$(document).on("click", "#new_p", function (e) {
    if (newrow == true) {
        return;
    }
    newrow = true;
    var dTable = $('#datatable_tabletools').DataTable();
    dTable.row.add([
            "<label id='Alert_Person_ID'></label>",
            "<span class='display-mode'><label id='lblFirstName'></label></span><input type='text' id='FirstName' class='edit-mode' />",
            "<span class='display-mode'><label id='lblLastName'></label></span><input type='text' id='LastName' class='edit-mode' />",
            "<span class='display-mode'><label id='lblPhonePrimary'></label></span><input type='text' id='PhonePrimary' class='edit-mode' />",
            "<span class='display-mode'><label id='lblEmailPrimary'></label></span><input type='text' id='EmailPrimary' class='edit-mode' />",
            "<span class='display-mode'><label id='lblCounty'></label></span><input type='text' id='County' class='edit-mode' />",
            "</button><button class='new-user edit-mode btn btn-xs btn-default'><i class='fa fa-save'></i></button><button class='abort-user edit-mode btn btn-xs btn-default'><i class='fa fa-times'></i></button>"
    ]).draw();
});

并且save-user按钮功能如下所示:

    $(document).on("click", ".save-user", function (e) {
        var tr = $(this).parents('tr:first');
        var FirstName = tr.find("#FirstName").val();
        var LastName = tr.find("#LastName").val();
        var PhonePrimary = tr.find("#PhonePrimary").val();
        var EmailPrimary = tr.find("#EmailPrimary").val();
        var County = tr.find("#County").val();
        var Alert_Person_ID = tr.find("#Alert_Person_ID").html();
        var AlertPerson =
        {
            "Alert_Person_ID": Alert_Person_ID,
            "FirstName": FirstName,
            "LastName": LastName,
            "PhonePrimary": PhonePrimary,
            "EmailPrimary": EmailPrimary,
            "County": County
        };
        $.ajax({
            url: '/AlertPerson/UpdatePerson/',
            data: JSON.stringify(AlertPerson),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                    tr.find("#lblFirstName").text(FirstName);
                    tr.find("#lblLastName").text(LastName);
                    tr.find("#lblPhonePrimary").text(PhonePrimary);
                    tr.find("#lblEmailPrimary").text(EmailPrimary);
                    tr.find("#lblCounty").text(County);
                    tr.find('.edit-mode, .display-mode').toggle();
                    noty({
                        text: data[1],
                        layout: "topCenter",
                        type: "success",
                        timeout: 2000
                    });

            },
            error: function(data){
                tr.find('.edit-mode, .display-mode').toggle();
                noty({
                    text: data[3] + "br/>" + data[4],
                    layout: "topCenter",
                    type: "warning",
                    timeout: 2000
                });                   
            }
        })
    });

我知道它有很多代码:O但这是一种简单的方法来向表中添加像这样(下)的JQuery验证吗?对于每个更新的行和添加的新行?

$(function() {
                // Validation
                $("#ID").validate({
                    // Rules for form validation
                    rules : {
                        FirstName : {
                            required : true
                        },
                        LastName : {
                            required : true
                        }
                    },

                    // Messages for form validation
                    messages : {
                        FirstName : {
                            required : 'Please enter First Name'
                        },
                        LastName : {
                            required : 'Please enter Last Name'
                        }
                    },

                    errorPlacement : function(error, element) {
                        error.insertAfter(element.parent());
                    }
                });
            });

1 个答案:

答案 0 :(得分:0)

我宁愿将此作为评论添加,但没有足够的声誉。这是根据评论中的建议将<form>元素中的每一行包装在其自己唯一的id中。

您不需要将每行包装在自己的<form>中 - 您可以将整个<table>包裹在<form>中。然后,为每个<input>添加jQuery不显眼的验证,只需添加必要的属性即可。 E.g:

<input type='text' data-val='true' data-val-required='Required'>

首先启用验证,然后根据需要使用“必需”验证消息标记此输入(如果未提供值)。如果您想知道MVC生成的标记,请使用模型执行测试页面,其中模型属性已使用您感兴趣的数据属性进行修饰,例如:正则表达式验证等一些例子可以帮助您:

正则表达式验证

<input type='text' id='newsletter-mobile' name='newsletter-mobile' data-val='true' data-val-regex='Not a valid mobile' data-val-regex-pattern='(^\+([^0-9]*?(\d)){9,15}$)|(^[^0-9]*?0[678]([^0-9]*?\d){8}$)' />

最大长度

<input type="email" id="emailaddress" name="emailaddress" data-val="true" data-val-required="Required field" data-val-length="Email must be a string with a maximum length of 60." data-val-length-max="60" />

两个字段必须匹配 - 另外说明了如何显示验证消息

<label for="password_273">Password <span>(Required)</span></label>
<input type="password" id="password_273" name="password_273" data-val="true" data-val-required="Required field" data-val-length="Password must be between 6 and 30 characters." data-val-length-max="30" data-val-length-min="6" />
<div><span class="field-validation-valid" data-valmsg-for="password_273" data-valmsg-replace="true"></span></div>
<label for="password2_273">Verify Password <span>(Required)</span></label><input type="password" id="password2_273" name="password2_273" data-val="true" data-val-required="Required field" data-val-equalto-other="password_273" data-val-equalto="Values must match!" />
<div><span class="field-validation-valid" data-valmsg-for="password2_273" data-valmsg-replace="true"></span></div>

在“保存”按钮上,首先应该通过Ajax或其他方式提交数据,然后对表单调用jQuery验证函数,例如:

var $frm = $('#form-id');
$frm.validate();
if (!$frm.valid())
  return;
//now you can save your data - but validate on the server again!

可能有用的补充说明:

  1. 如果您没有看到有关验证失败的任何视觉反馈,请确保为类input.input-validation-error定义样式 - jQuery验证只是将此类添加到未通过验证的元素,由您自行决定他们脱颖而出。
  2. 如果您发现验证根本不起作用,可能是因为jQuery验证未检测到动态添加的input元素,例如由AJAX加载。要对此输入启用验证,您需要实现在another question的答案中建议的小插件。