繁体   English   中英

MVC模型验证中的变量

[英]Variables in model validation on MVC

因此,在使用.NET Membership系统的MVC中,密码策略在web.config文件中定义。 例如,minPasswordLength在membership - >配置文件中定义。

使用View时,可以使用@Membership组件访问@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建议),还要搜索在源代码中对它的任何引用并在整个地方进行更改(可能不是最好的编程实践)。

有没有在Attributes中使用变量的方法。 我怀疑不是因为这可能发生在编译时而不是运行时。 如果没有人知道更好的模式,以阻止我在将来找到替换所有引用?

这篇文章可以帮助您回答问题。 基本上,创建自己的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)
        };
    } 
}

在您的ViewModel上

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

如果要将可变参数用于验证属性,则需要开发自己的属性并应用它。

也许称之为“MinLengthFromConfigFile”?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM