ASP .Net MVC 3:自定义非侵入性验证

发布于 2025-01-04 17:03:25 字数 714 浏览 3 评论 0原文

我正在尝试向我的应用程序添加自定义的不引人注目的验证。它似乎没有运行验证。

这是我的 Attribute 类:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
{
    yield return new ModelClientValidationRule
    {
        ErrorMessage = ErrorMessage,
        ValidationType = "custrequired"
    };
}

和我的 JavaScript:

$.validator.addMethod('custrequired', function(value, element, param) {
  return value && value !== '99:99' && value !== '9:99';
});

$.validator.unobtrusive.adapters.add('custrequired', null, function(options) {
  return options.messages['custrequired'] = options.message;
});

I am trying to add a custom unobtrusive validation to my app. It does not seem to run the validation.

Here is my Attribute class:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
{
    yield return new ModelClientValidationRule
    {
        ErrorMessage = ErrorMessage,
        ValidationType = "custrequired"
    };
}

And my JavaScript:

$.validator.addMethod('custrequired', function(value, element, param) {
  return value && value !== '99:99' && value !== '9:99';
});

$.validator.unobtrusive.adapters.add('custrequired', null, function(options) {
  return options.messages['custrequired'] = options.message;
});

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

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

发布评论

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

评论(4

北斗星光 2025-01-11 17:03:25

这里有很多地方可能会出错,但没有一个涉及您发布的代码:

  • 您为 生成的 HTML 看起来如何?它是否包含 data-val-custrequired 属性?

  • 如果没有,您是否记得在类声明中添加接口 - IClientValidatable

  • 您是否记得DOM 就绪 处理程序中添加自定义验证器? (即不要使用 $(document).ready()$(function() { ... })) - 验证应在文档已准备就绪。

ETA:最后一个的原因是 jquery.validate.unobtrusive 这样做:

$(function () {
    $jQval.unobtrusive.parse(document);
});

即,它在文档准备好时解析文档以获取验证属性、规则等。由于必须加载该脚本才能注册您的适配器,因此您的注册脚本通常必须位于之后jquery.validate.unobtrusive.js。但这也使得您注册的任何 .ready 处理程序“不引人注目”的处理程序之后被调用 - 到那时就为时已晚了。我想你可以把你的注册脚本放在前面,然后使用.ready。我从未尝试过,也从未见过它被完成。

另外,在这种情况下,这应该足以注册适配器:

$.validator.addMethod('custrequired', function(value, element, param) {
   return value && value !== '99:99' && value !== '9:99';
});

jQuery.validator.unobtrusive.adapters.addBool('custrequired');

它仍然会添加您可能有的任何自定义错误消息,但由于您的验证器没有使用其他参数(例如 StringLength 传递 < code>MaximumLength 等),不需要自定义适配器。

There are plenty of things that can go wrong here, none involving the code you've posted:

  • How does your generated HTML for the <input> look? Does it include the data-val-custrequired attribute?

  • If not, did you remember to add the interface in the class declaration - IClientValidatable?

  • Did you remember to not add your custom validator inside a DOM ready handler? (i.e. don't use $(document).ready() or $(function() { ... })) - the validation should be set up before the document is ready.

ETA: The reason for the last one is that jquery.validate.unobtrusive does this:

$(function () {
    $jQval.unobtrusive.parse(document);
});

I.e., it parses the document for validation attributes, rules etc. on document ready. Since that script has to be loaded in order to register your adapters, your registration script would normally have to come after jquery.validate.unobtrusive.js. But that also makes any .ready handler you register be called after the "unobtrusive" one - by which point it's too late. I guess you could put your registration script before and then use .ready. Never tried it, and I've never seen it done.

Also, in this case, this should be enough to register the adapter:

$.validator.addMethod('custrequired', function(value, element, param) {
   return value && value !== '99:99' && value !== '9:99';
});

jQuery.validator.unobtrusive.adapters.addBool('custrequired');

It will still add any custom error message you may have, but since your validator isn't using additional parameters (like e.g. StringLength passes MaximumLength etc.), there's no need for a custom adapter.

七颜 2025-01-11 17:03:25

$.validator.unobtrusive.adapters.add 调用存在一些问题:

$.validator.unobtrusive.adapters.add('custrequired', function (options) {
// -------------------------------------------------^ <-- removed "null" param
    options.messages['custrequired'] = options.message;
    // Register the rule properly
    options.rules['custrequired'] = options.params;
    // Don't return anything
});

在这两项更改之后(并确保在 web.config 中启用了 ClientValidation 和 UnobtrusiveJavascript),一切正常。

There are a few problems with the $.validator.unobtrusive.adapters.add call:

$.validator.unobtrusive.adapters.add('custrequired', function (options) {
// -------------------------------------------------^ <-- removed "null" param
    options.messages['custrequired'] = options.message;
    // Register the rule properly
    options.rules['custrequired'] = options.params;
    // Don't return anything
});

After those two changes (and making sure ClientValidation and UnobtrusiveJavascript were enabled in the web.config), things worked fine.

卸妝后依然美 2025-01-11 17:03:25

您必须更改服务器端。

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
    {
      //I changed ErrorMessage for ErrorMessageString
      yield return new ModelClientValidationRule
      {
        ErrorMessage = ErrorMessageString,
        ValidationType = "custrequired"
      };
   }

正如安德烈·惠特克所说,您必须将其添加到客户端以进行验证。

    //i changed param for params
    $.validator.addMethod('custrequired', function(value, element, params) {
       return value && value !== '99:99' && value !== '9:99';
    });

    //i specified that there isn't paramaters using an empty array.
    $.validator.unobtrusive.adapters.add('custrequired', [] , function (options) {
        options.messages['custrequired'] = options.message;
        options.rules['custrequired'] = options.params;
    });

记住检查输入的 HTML,它应该具有“data-”属性和您的错误消息文本

我希望它对您有用。

You have to change the server side.

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
    {
      //I changed ErrorMessage for ErrorMessageString
      yield return new ModelClientValidationRule
      {
        ErrorMessage = ErrorMessageString,
        ValidationType = "custrequired"
      };
   }

And also as Andre Whitaker said you have to put this for add your validation to the clien side.

    //i changed param for params
    $.validator.addMethod('custrequired', function(value, element, params) {
       return value && value !== '99:99' && value !== '9:99';
    });

    //i specified that there isn't paramaters using an empty array.
    $.validator.unobtrusive.adapters.add('custrequired', [] , function (options) {
        options.messages['custrequired'] = options.message;
        options.rules['custrequired'] = options.params;
    });

REMEMBER TO CHECK THE HTML OF THE INPUT, IT SHOULD HAVE THE "data-" ATTRIBUTE WITH YOUR ERROR MESSAGE TEXT

I hope it works for you.

a√萤火虫的光℡ 2025-01-11 17:03:25

经过一些研究,我在 Asp.Net Mvc 中找到了一个很好的自定义非侵入性和服务器端验证解决方案。检查以下链接

雷蒙德·马卡拉莱

After some research I found a good solution for custom unobtrusive and server side validation in Asp.Net Mvc. Check the below link

Raymund Macaalay

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