【问题标题】:JQuery Autocomplete Combobox: MVC3 Validation not workingJQuery 自动完成组合框:MVC3 验证不起作用
【发布时间】:2012-08-09 18:56:42
【问题描述】:

我正在尝试将JQuery UI Autocomplete (Combobox) 与 ASP.NET MVC3 中的下拉列表一起使用。

这是我认为的相关代码部分:

    <div class="editor-label">
        @Html.LabelFor(model => model.MerchantID, "Merchant")
    </div>
    <div class="editor-field">
        @Html.DropDownList("MerchantID", null, String.Empty, new { @class = "combobox" })
        @Html.ValidationMessageFor(model => model.MerchantID)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.FinancialAccountID, "FinancialAccount")
    </div>
    <div class="editor-field">
        @Html.DropDownList("FinancialAccountID", null, String.Empty, new { @class = "combobox" })
        @Html.ValidationMessageFor(model => model.FinancialAccountID)
    </div>

(有 4-10 个下拉列表。)

这里是javascript文件的内容,基本上是从jquery-ui website复制过来的:

(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var input,
                    self = this,
                    select = this.element.hide(),
                    selected = select.children(":selected"),
                    value = selected.val() ? selected.text() : "",
                    wrapper = this.wrapper = $("<span>")
                        .addClass("ui-combobox")
                        .insertAfter(select);

            input = $("<input>")
                    .appendTo(wrapper)
                    .val(value)
                    .addClass("ui-state-default ui-combobox-input")
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: function (request, response) {
                            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                            response(select.children("option").map(function () {
                                var text = $(this).text();
                                if (this.value && (!request.term || matcher.test(text)))
                                    return {
                                        label: text.replace(
                                            new RegExp(
                                                "(?![^&;]+;)(?!<[^<>]*)(" +
                                                $.ui.autocomplete.escapeRegex(request.term) +
                                                ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                            ), "<strong>$1</strong>"),
                                        value: text,
                                        option: this
                                    };
                            }));
                        },
                        select: function (event, ui) {
                            ui.item.option.selected = true;
                            self._trigger("selected", event, {
                                item: ui.item.option
                            });
                        },
                        change: function (event, ui) {
                            if (!ui.item) {
                                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                    valid = false;
                                select.children("option").each(function () {
                                    if ($(this).text().match(matcher)) {
                                        this.selected = valid = true;
                                        return false;
                                    }
                                });
                                if (!valid) {
                                    // remove invalid value, as it didn't match anything
                                    $(this).val("");
                                    select.val("");
                                    input.data("autocomplete").term = "";
                                    return false;
                                }
                            }
                        }
                    })
                    .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a>" + item.label + "</a>")
                        .appendTo(ul);
            };

            $("<a>")
                    .attr("tabIndex", -1)
                    .attr("title", "Show All Items")
                    .appendTo(wrapper)
                    .button({
                        icons: {
                            primary: "ui-icon-triangle-1-s"
                        },
                        text: false
                    })
                    .removeClass("ui-corner-all")
                    .addClass("ui-corner-right ui-combobox-toggle")
                    .click(function () {
                        // close if already visible
                        if (input.autocomplete("widget").is(":visible")) {
                            input.autocomplete("close");
                            return;
                        }

                        // work around a bug (likely same cause as #5265)
                        $(this).blur();

                        // pass empty string as value to search for, displaying all results
                        input.autocomplete("search", "");
                        input.focus();
                    });
        },

        destroy: function () {
            this.wrapper.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);

$(function () {
    $(".combobox").combobox();
});

我遇到的问题是似乎没有对输入的值进行任何验证。例如,如果我将其留空并提交,则没有错误表明输入了无效信息。但是,如果我注释掉 combobox() 调用以禁用组合框功能,则验证工作正常。

我已经针对这个问题在 stackoverflow 上进行了一些搜索,但我似乎找不到任何符合这种特定情况的内容。

编辑:我发现验证确实会发生,但前提是我在提交之前单击另一个字段,这很奇怪。因此,如果我在组合框中输入空白文本,然后单击文本字段,然后提交,它可以正常工作(显示验证错误。)但是如果我在组合框中输入空白文本并提交,它不会显示验证错误。有任何想法吗?

【问题讨论】:

  • 我在您的代码和 jquery 示例之间看到的唯一区别是您按类而不是 ID 应用组合框函数。您是否尝试过仅按 ID 将其应用于单个元素?
  • @Shawn 谢谢你的回复。我尝试了您的建议,但不幸的是行为没有改变。但是,我确实观察到了有关该问题的更多详细信息,并将其添加到我的帖子中。我发现验证确实发生了,但前提是我在提交之前单击另一个字段,这很奇怪。因此,如果我在组合框中输入空白文本,然后单击文本字段,然后提交,它可以正常工作(显示验证错误。)但是如果我在组合框中输入空白文本并提交,它不会显示验证错误。有什么想法吗?

标签: jquery asp.net-mvc-3 jquery-ui validation jquery-ui-autocomplete


【解决方案1】:

好的,我发现了问题。

当按下提交按钮时,在检测到错误输入时清除所选项目的自动完成 JQuery之前调用了 javascript 验证。这是我的意思:

if (!valid) {
     // remove invalid value, as it didn't match anything
     $(this).val("");
     select.val("");
     input.data("autocomplete").term = "";
     return false;
}

所以我在用户开始输入时就明确了选定的项目,并且只有在选择了有效项目时才重新选择。

source: function (request, response) {
    select.val(""); //as soon as typing is started, the select input is cleared.  This makes sure validation always occurs
    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
    response(select.children("option").map(function () {
        var text = $(this).text();
        if (this.value && (!request.term || matcher.test(text)))
            return {
                label: text.replace(
                    new RegExp(
                        "(?![^&;]+;)(?!<[^<>]*)(" +
                        $.ui.autocomplete.escapeRegex(request.term) +
                        ")(?![^<>]*>)(?![^&;]+;)", "gi"
                    ), "<strong>$1</strong>"),
                value: text,
                option: this
            };
    }));
},

【讨论】:

  • 这很有帮助,这2个函数你在哪里包含?
  • @learning 我的原始问题显示了完整的 javascript 代码,需要以某种方式(可能通过捆绑包)包含在页面中。我的回答只是更改了该代码的一部分(源参数自动完成功能。)另外,作为一个警告,我还没有在较新版本的 jQuery、jQuery UI 或 ASP.NET MVC 上对此进行测试。
  • 我使用的解决方案在下面的链接中。我确实喜欢立即清除输入,我将此添加到我的组合框 +1 stackoverflow.com/questions/13516841/…
猜你喜欢
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
相关资源
最近更新 更多