2012-06-25 52 views
4

所以在使用.NET Membership系统的MVC中,密码策略是在web.config文件中定义的。例如minPasswordLength在成员资格 - >配置文件中定义。MVC模型验证的变量

当使用视图,这是访问使用@Membership组件

Passwords must be at least @Membership.MinRequiredPasswordLength characters long. 

但是,如果你看一下在本例中的默认模型MVC应用程序,它说

[Required] 
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
[DataType(DataType.Password)] 
[Display(Name = "New Password")] 
public string NewPassword { get; set; } 

我很好奇的部分是MinimumLength = 6,因为这是硬编码,这意味着如果我想更新密码长度,我不仅需要编辑web.config(如Microsoft建议),还要搜索源代码中的任何引用,以及改变所有的o这个地方(可能不是最好的编程习惯)。

有什么方法在属性中使用变量。我怀疑没有,因为这可能发生在编译时而不是运行时。如果没有人知道有更好的模式可以阻止我在将来找到所有的参考文献吗?

回答

8

Here is an article可以帮助你回答你的问题。基本上,创建自己的DataAnnotation,从web.config中获取最小长度。

对于后人,这里所引用的网站使用的代码:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter , AllowMultiple = false, Inherited = true)] 
public sealed class MinRequiredPasswordLengthAttribute : ValidationAttribute, IClientValidatable 
{       
    private readonly int _minimumLength = Membership.MinRequiredPasswordLength;   
    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _minimumLength); 
    } 
    public override bool IsValid(object value) 
    {   
     string password = value.ToString(); 
     return password.Length >= this._minimumLength;    
    }   
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     return new[]{ 
      new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minimumLength, int.MaxValue) 
     }; 
    } 
} 

,并在您的视图模型

[Required]   
[MinRequiredPasswordLength(ErrorMessage = "The {0} must be at least {1} character(s) long.")]   
[DataType(DataType.Password)] 
[Display(Name = "Password")] 
public string Password { get; set; } 
+0

干得好汤米:) –