【问题标题】:Using parameter for StringLength attribute使用 StringLength 属性的参数
【发布时间】:2013-08-31 12:05:19
【问题描述】:

通常为 ASP.NET MVC 3 Membership 生成的代码,尤其是 ChangePasswordModel 类的属性 NewPassword 大致如下:

    [Required]
    [StringLength(100, MinimumLength=6)]
    [DataType(DataType.Password)]
    [Display("Name = CurrentPassword")]
    public string NewPassword { get; set; }

为了使用外部参数填充一些信息,我正在使用 RecourceType:
(在这种情况下,我正在更改 OldPassword 并使用来自资源的一些额外数据填充属性 Display

    [Required]
    [DataType(DataType.Password)]
    [Display(ResourceType = typeof(Account), Name = "ChangePasswordCurrent")]
    public string OldPassword { get; set; }

返回NewPassword如何将MinimumLenght 替换为Membership.MinRequiredPasswordLength:我的尝试:

    [Required]
    [StringLength(100, MinimumLength=Membership.MinRequiredPasswordLength)] 
    [DataType(DataType.Password)]
    [Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
    public string NewPassword { get; set; }

这会产生错误:

属性参数必须是常量表达式,typeof 表达式 或属性参数类型的数组创建表达式 (http://msdn.microsoft.com/de-de/library/09ze6t76%28v=vs.90%29.aspx)

【问题讨论】:

标签: c# asp.net asp.net-mvc-3 localization asp.net-membership


【解决方案1】:

验证属性必须是编译常量(如您的错误消息状态)。您可以创建自己的 ValidationAttribute 来为您处理这个最小长度。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
{

    private const string DefaultErrorMessage = "'{0}' must be at least {1} characters long.";

    private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
    public ValidatePasswordLengthAttribute() : base(DefaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, _minCharacters);
    }

    public override bool IsValid(object value)
    {
        var valueAsString = value.ToString();
        return (valueAsString != null) && (valueAsString.Length >= _minCharacters);
    }
}

然后您的视图模型可能看起来像这样(您甚至可以更花哨,并在 ValidatePasswordLength 属性中添加 DataAnnotations 的最大长度部分以删除该行)

[Required]
[StringLength(100)] 
[DataType(DataType.Password)]
[Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
[ValidatePasswordLength]
public string NewPassword { get; set; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 2012-07-09
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多