通常为ASP.NET MVC 3 Membership生成的代码,特别是类NewPassword
的属性ChangePasswordModel
看起来大致如下:
[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)
答案 0 :(得分:3)
验证属性必须是已编译的常量(如错误消息状态)。您可以创建自己的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; }