【问题标题】:custom server side validation c#自定义服务器端验证 c#
【发布时间】:2018-07-23 03:28:55
【问题描述】:

我对此并不陌生,并为服务器端的字符串长度验证创建了一个自定义属性。例如我有这个

 [StringLength(5, MinimumLength = 2, ErrorMessageResourceName = "StringLength", ErrormessageResourceType = typeof(Resource))]
 public string LastName { get; set; }

我想创建一个自定义属性,这样我可以在每次需要验证字符串长度时减少重复项

[MyStringLength(5)]
public string LastName { get; set; }

这是我的看法

@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)

自定义属性“MyStringLength”的代码

 public class MyStringLengthAttribute : StringLengthAttribute
{

    public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
    {         
        base.ErrorMessageResourceName = "StringLength";
        base.ErrorMessageResourceType = typeof(Resource);
    }
}

这对我有帮助 Modify default ErrorMessage for StringLength validation 但在我发布表单后它只是用值刷新页面并且不显示任何验证消息

【问题讨论】:

  • 您应该在您的尝试中提供您的代码,而不是关联另一个声称它不起作用的问题。也许是你实现它的方式不起作用。
  • 什么是MyStringLengthAttribute
  • @RonBeyer 这是我创建的自定义属性的名称。这是我的代码 public class MyStringLengthAttribute : StringLengthAttribute { public MyStringLengthAttribute(int maximumLength) : base(maximumLength) { base.ErrorMessageResourceName = "StringLength"; base.ErrorMessageResourceType = typeof(Resource); } }
  • @Guilherme ty 抽出时间。我编辑了我的问题以获得我的自定义属性的代码。
  • 您需要在global.asax.cs 中注册您的属性才能使用它。

标签: c# asp.net-mvc


【解决方案1】:

我需要一个用于客户端验证的适配器并在我的 global.asax.cs 中注册自定义属性。请看Client-side validation for custom StringLength validation attribute

【讨论】:

  • 您不需要适配器 - 已经内置了一个。它只是 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyStringLength), typeof(StringLengthAttributeAdapter));。并在您的答案中添加代码,而不是链接
  • @StephenMuecke 我不知道为什么我没想到。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 2013-02-27
  • 1970-01-01
相关资源
最近更新 更多