【问题标题】:Get the current length from StringLengthAttribute in C#从 C# 中的 StringLengthAttribute 获取当前长度
【发布时间】:2015-01-07 19:54:19
【问题描述】:

我在模型中有 ASP.NET 网站属性:

[Required]
[Display(Name = "bla bla")]
[MinMaxLength(50,2000)]
public string TextDetail { get; set; }

我已经本地化了

public class MinMaxLengthAttribute : StringLengthAttribute
{
    public MinMaxLengthAttribute(int minimum, int maximum)
       :base(maximum)
    {
        ErrorMessage = "{0} must contain from  {2} to {1} characters."; //this text is localized, that is why I need to use special class
        MinimumLength = minimum;
    }
}

当我查看日志时,我可以找到

Exception (level 0):
Message = bla bla must contain from 50 to 2000 characters.

如果用户写的字符串太短或太长,我想记录。有没有办法在 StringLengthAttribute 中记录字符串的当前长度?

【问题讨论】:

  • 为什么要创建 MinMaxLengthAttribute?为什么不使用 StringLengthAttribute?
  • 因为 StringLengthAttribute 仅适用于英文网站,请参阅评论。据我所知,我必须对自定义本地化消息进行此类自定义。如果有简单的解决方案,请告诉我。
  • 我们一直使用资源文件来获取本地化错误消息。为什么StringLengthAttribute的错误信息也不能做到这一点?

标签: asp.net-mvc validation data-annotations


【解决方案1】:

您可以使用StringLengthAttribute,如下所示:

[Required]
[Display(Name = "bla bla")]
[StringLength(20000, MinimumLength = 50, ErrorMessage = "{0} must contain from  {2} to {1} characters.")]
public string TextDetail { get; set; }

而且,如果你想显示当前的无效值,你可以使用 jQuery。不需要服务器端代码来做这么简单的事情。

【讨论】:

  • 是的,您的解决方案对于自定义本地化消息更简单。这也很好。但我不想一次又一次地复制本地化文本。我只想拥有一个数据注释本地化的地方。问题是关于记录/跟踪用户的行为。我只想从日志中知道,他们在表单中输入了太短或太长的字符串。
【解决方案2】:

最后,解决方法很简单:

public class MinMaxLengthAttribute : StringLengthAttribute
{
    int? _stringLength = null;

    public MinMaxLengthAttribute(int minimum, int maximum)
        : base(maximum)
    {
        SetErrorMessage();
        MinimumLength = minimum;
    }

    void SetErrorMessage()
    {
        ErrorMessage = "{0} must contain {2} to {1} characters." +
               " It contains " + (_stringLength ?? -1) + " characters.";
    }

    public override bool IsValid(object value)
    {
        string s = value as string;
        if (s != null)
        {
            _stringLength = s.Length;
            SetErrorMessage();
        }

        return base.IsValid(value);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string s = value as string;
        if (s != null)
        {
            _stringLength = s.Length;
            SetErrorMessage();
        }

        return base.IsValid(value, validationContext);
    }        
}

还有单元测试:

using Common.Validators;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Test.Model
{
    [TestClass]
    public class UnitTestDtaValidation
    {
        [TestMethod]
        public void TestMinMaxLengthAttribute()
        {
            MyModel model = new MyModel()
            {
                TextDetail = "a"
            };

            var validationContext = new ValidationContext(model, serviceProvider: null, items: null);
            var results = new List<ValidationResult>();
            var isValid = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, validationContext, results, true);

            Assert.IsFalse(isValid);

            Assert.AreEqual(1, results.Count);

            Assert.AreEqual("Description must contain from 5 to 10 characters. It contains 1 characters.", results[0].ErrorMessage);
        }
    }

    public class MyModel
    {
        [Required]
        [Display(Name = "Description")]
        [MinMaxLength(5, 10)]
        public string TextDetail { get; set; }
    }

}

【讨论】:

  • 我相信我们对“相当简单”有不同的定义,尤其是在复制 C# 中已有的功能时。
【解决方案3】:

StringLengthAttribute 类继承自 ValidationAttribute,可以使用 ErrorMessageResourceType 和 ErrorMessageResourceName 从资源字符串本地化。所以你的例子变成了:

public class MyModel
{
    [Required]
    [Display(Name = "Description")]
    [StringLength(10, MinimumLength = 5, ErrorMessageResourceType = typeof(MyStringsResource), ErrorMessageResourceName = "MyTextDetailErrorMessage"]
    public string TextDetail { get; set; }
}

在您本地化的MyStringsResource 资源中,将一个名为MyTextDetailErrorMessage 的字符串设置为"{0} must contain {2} to {1} characters."。

如果您在派生类中需要更动态的消息,您可以使用受保护的重载ValidationAttribute(Func&lt;string&gt; errorMessageAccessor) 构造您的MinMaxLengthAttribute 实例,以便提供一个函数来查找错误消息。抱歉,我没有经验可分享。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2021-12-22
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多