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

发布于 2024-12-04 04:42:08 字数 470 浏览 0 评论 0原文

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

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

@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?
 }

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.

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?
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灰色世界里的红玫瑰 2024-12-11 04:42:08

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

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

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

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

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:

var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
方圜几里 2024-12-11 04:42:08

您还可以执行以下操作:

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

在代码中使用此函数:

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");
            }
        }
    }

然后可以设置错误

setError("Slug", "errorMsg");

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");
送你一个梦 2024-12-11 04:42:08

使用 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";
});

用法:

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

将其恢复到有效状态:

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

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.

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'), '');
铁憨憨 2024-12-11 04:42:08

在我看来,接受的答案有两个使其毫无用处的大问题:

  1. 它不会将输入的状态更改为无效。因此,用户可以自由提交该表格。
  2. 一旦接下来验证输入,例如在输入的下一个键盘事件上,它将被清除。

kevinpo 的答案解决了这两个问题,如果您需要动态生成,可能应该使用它。 > 错误消息。但静态错误消息通常已经足够好了,所以...

让我们通过不引人注目的验证使这变得非常简单。

将其添加到站点范围的 javascript 文件中:

$.fn.extend({
  toggleOk: function (value) {
    this[0].dataset.ok = value;
    this.valid();
  }
});

$.validator.addMethod("ok", function (value, element) {
  return this.optional(element) || $(element)[0].dataset.ok === "true";
});

$.validator.unobtrusive.adapters.addBool("ok");

将其添加到 HTML 中的相关输入元素。第一个属性 data-val-ok 告诉非侵入性验证为此输入激活这种类型的验证,并告诉它在无效时显示什么错误消息。第二个属性 data-ok 将初始状态设置为有效。

data-val-ok="That item does not exist." data-ok="true"

在页面的 Javascript 中调用此代码可将输入设置为无效、显示错误和相关格式并阻止页面提交。

$('#myInput').toggleOk(false);

调用此命令将其更改回有效状态,隐藏错误和相关格式,并允许页面提交:

$('#myInput').toggleOk(true);

The accepted answer has two big problems that make it useless, in my opinion:

  1. It doesn't change the input's state to invalid. Therefore, the user is free to submit the form.
  2. It will be wiped out as soon as the input is validated next, such as on the input's next keyboard event.

kevinpo's answer addresses both of these problems and is probably what you should use if you need dynamically-generated error messages. But static error messages are usually good enough, so...

Let's make this really simple this with unobtrusive validation.

Add this to your site-wide javascript file:

$.fn.extend({
  toggleOk: function (value) {
    this[0].dataset.ok = value;
    this.valid();
  }
});

$.validator.addMethod("ok", function (value, element) {
  return this.optional(element) || $(element)[0].dataset.ok === "true";
});

$.validator.unobtrusive.adapters.addBool("ok");

Add this to the relevant input element in your HTML. The first attribute, data-val-ok, tells unobtrusive validation to activate this type of validation for this input and tells it what error message to show when it is invalid. The second attribute, data-ok, sets the initial state to valid.

data-val-ok="That item does not exist." data-ok="true"

Call this code in your page's Javascript to set the input to invalid, display the error and related formatting, and block page submission.

$('#myInput').toggleOk(false);

Call this to change it back to valid, hide the error and related formatting, and permit page submission:

$('#myInput').toggleOk(true);
泪意 2024-12-11 04:42:08

这是对 FRL 答案的改进:

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

JS Function

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 like this:

setError("Slug", "errorMsg");

This is an improvement on FRL's answer:

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

JS Function

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 like this:

setError("Slug", "errorMsg");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文