如何为使用jQuery呈现的UI元素设置不显眼的验证

时间:2018-02-02 08:04:01

标签: javascript jquery asp.net-mvc razor unobtrusive-validation

我有一个Razor视图,使用HTML帮助器和其他人使用jQuery DataTable

呈现一些下降
<div class="form-group">
            @Html.LabelFor(model => model.CarTyres, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-2">
                @Html.ListBoxFor(model => model.SelectedCarTyres, Model.CarTyres, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
                @Html.ValidationMessageFor(model => model.SelectedCarTyres, "", new { @class = "text-danger" })

            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Drivers, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-2">
                @Html.ListBoxFor(model => model.SelectedDrivers, Model.Drivers, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
                @Html.ValidationMessageFor(model => model.SelectedDrivers, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.CarJacks, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-5">
                <table id="filtersTable">
                    <thead>
                        <tr>
                            <th>Select</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                </table>
            </div>
            @Html.ValidationMessageFor(model => model.CarJacksCheckBox, "", new { @class = "text-danger" })
        </div>

在我的模型中,我将required设置为true,这样当我检查时Model.IsValid()将返回false,如果没有设置任何这些项,那就可以了。

  public class ReportViewModel
    {
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }


        [Required]
        public ICollection<int> SelectedCarTyres { get; set; }
        public IEnumerable<SelectListItem> CarTyres { get; set; }

        [Required]
        public ICollection<int> SelectedDrivers { get; set; }
        public IEnumerable<SelectListItem> Drivers { get; set; }


        public IEnumerable<CarJackViewModel> CarJacks { get; set; }

        [Required]
        public string SelectedSampleTime { get; set; }
        public IEnumerable<SelectListItem> SampleTimes { get; set; }



        [Required]
        public IEnumerable<int> CarJacksCheckBox { get; set; }


    }

为了使javascrip数据表成为必需,我在复选框上复制了vallidation属性,如下所示:

 $('#filtersTable').DataTable(
        {
            "iDisplayLength": 25,
            "ajax": {
                "url": "/CarJacks/Loaddata",
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
                {
                    "data": "IsSelected",
                    "render": function (data, type, row) {
                        if (type === 'display') {
                            return '<input type="checkbox" name="CarJacksCheckBox" class="editor-active" data-val="true"  data-val-required="The CarJacks field is required.">';
                        }
                        return data;
                    }

            ],
            "rowCallback": function (row, data) {
                //Removed for Brevity
            }
        }
    );

但是,当没有选择任何CarJackCheckBox时,我没有得到任何客户端验证。

虽然(ModelState.IsValid)返回false,但$(form).valid()返回true,因此客户端没有错误。

我错过了哪一件?

2 个答案:

答案 0 :(得分:2)

您不能使用MVC的客户端验证,因为验证规则应用于表单控件,而您不能(也不能)为IEnumerable<int> CarJacksCheckBox属性创建表单控件。您需要编写自己的脚本来验证是否至少需要一个复选框。

从复选框中删除data-val-*属性(因为它们毫无意义)并添加一个额外的类名,比如说carjacks在脚本中用作jQuery选择器。

然后包括以下脚本(注意这些模仿'懒惰'验证 - 它首先在提交时验证,然后在单击复选框时验证)

var validateOnClick = false; // for lazy validation
var requiredCarJacks = 1;
var carJacks= $('.carjacks');
var errorMessage = 'Select at least 1 car jack';
var errorElement = $('span[data-valmsg-for="CarJacksCheckBox"]');

function validateCarJacks() {
    var selectedCarJacks = carJacks.filter(':checked').length;
    var isValid = selectedCarJacks > requiredCarJacks ;
    if (!isValid) {
        errorElement.addClass('field-validation-error').removeClass('field-validation-valid').text(errorMessage);
    } else {
        errorElement.addClass('field-validation-valid').removeClass('field-validation-error').text('');
    }
    return (isValid);
}

$('form').submit(function () {
    if (!validateCarJacks()) {
        validateOnClick = true; // signal that we should now validate the .click() event
        return false; // prevent submit
    }
});

carJacks.click(function() {
    if (validateOnClick) {
        validateCarJacks();
    }
})

答案 1 :(得分:0)

初始化jQuery DataTable后必须添加一行。

$.validator.unobtrusive.parse('form')

此外,您可以使用jQuery Selector

$.validator.unobtrusive.parse('#formTable')