jQuery 在文本框上手动设置不显眼的验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7380278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:45:40  来源:igfitidea点击:

Manually set unobtrusive validation error on a textbox

jqueryasp.net-mvcasp.net-mvc-3jquery-validateunobtrusive-validation

提问by Shawn Mclean

I'm doing something similar to the remote validation, except that I already make my calls manually via jquery and setup whatever I had to setup.

我正在做类似于远程验证的事情,除了我已经通过 jquery 手动调用并设置了我必须设置的任何内容。

Now my problem is, if I want to tell the validator that a particular textbox is not valid (and prevents the page from submitting, highlight the textbox, etc). How would I do this from code?

现在我的问题是,如果我想告诉验证器某个特定的文本框无效(并阻止页面提交,突出显示文本框等)。我将如何从代码中做到这一点?

@Html.LabelFor(m => Model.Slug)
@Html.TextBoxFor(m => Model.Slug)
<span id="UrlMsg" class="field-validation-error" style="display: none;"></span>

 if (error) {
        $('#UrlMsg').html('This name is already in use.').fadeIn('fast');
        //what should I do here for the rest of the validation?
 }

回答by SkipHarris

First, you can add a validation summary:

首先,您可以添加验证摘要:

@Html.ValidationMessageFor(m => m.Slug)

Then you can manually trigger jQuery validation / unobtrusive validation with the .showError method. Here is a sample:

然后您可以使用 .showError 方法手动触发 jQuery 验证/非侵入式验证。这是一个示例:

var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);

回答by FRL

You can also do:

你也可以这样做:

@Html.ValidationMessageFor(m => m.Slug)

With this function in your code:

在您的代码中使用此功能:

function setError(id, message) {
        var span = $("span[data-valmsg-for=\"" + id + "\"]");
        if (span && span.length > 0) {
            $(span).html(message);
            if (message && message != "") {
                $(span).removeClass("field-validation-valid");
                $(span).addClass("field-validation-no-valid");
            } else {
                $(span).removeClass("field-validation-no-valid");
                $(span).addClass("field-validation-valid");
            }
        }
    }

Then can set the error

然后可以设置错误

setError("Slug", "errorMsg");

回答by shlgug

This is an improvement on FRL's answer:

这是对 FRL 答案的改进:

@Html.ValidationMessageFor(m => m.Slug)

JS Function

JS函数

        const span = $('span[data-valmsg-for="' + name + '"]');
        function setError(name, message) {
            const span = $(`span[data-valmsg-for="${name}"]`);
            if (span && span.length > 0) {
                $(span).html(message);
                if (message) {
                    $(`input[name="${name}"]`).addClass("input-validation-error");
                    $(span).removeClass("field-validation-valid");
                    $(span).addClass("field-validation-error");
                } else {
                    $(`input[name="${name}"]`).removeClass("input-validation-error");
                    $(span).removeClass("field-validation-error");
                    $(span).addClass("field-validation-valid");
                }
            }
        }

Call it

称它为

    setError("Slug", "errorMsg");

回答by kevinpo

Using showErrors did not allow the error to persist, so that running .valid() cleared the error. Instead, I added a "forcibleerror" rule and a javascript method to set the message.

使用 showErrors 不允许错误持续存在,因此运行 .valid() 清除了错误。相反,我添加了一个“forcibleerror”规则和一个 javascript 方法来设置消息。

function forceError(element, errorMessage) {
    $(element).rules("add", {
        forcibleerror: true,
        messages: {
            forcibleerror: function () { return errorMessage; }
        }
    });
    var isForced = false;
    if (errorMessage) {
        isForced = true;
    }
    $(element)[0].dataset.isForced = isForced;
    $(element).valid();
}
$.validator.addMethod("forcibleerror", function (value, element) {
    return $(element)[0].dataset.isForced !== "true";
});

Usage:

用法:

forceError($('#Slug'), 'my custom message');

To put it back in a valid state:

要将其恢复为有效状态:

forceError($('#Slug'), '');