Variables in model validation on MVC

So, in MVC, when using the .NET Membership system, password policies are defined in the web.config file. For example, minPasswordLength is defined in membership-> profiles.

When using View, this is available using the @Membership component

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

However, if you look at the default model in the MVC application example, it says

  [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; } 

The parts that interest me are MinimumLength = 6 , since it is hardcoded, it would mean that if I ever wanted to update the password length, I would have to not only edit web.config (e.g. Microsoft) but also look any references to it in the source and modify everywhere (perhaps not the best programming practice).

Are there any ways to use variables in attributes. I suspect that since this probably happens at compile time and not at runtime. If not, does anyone know a better pattern to stop me from finding a replacement for all links in the future?

+4
source share
2 answers

Here is an article to help you answer your questions. Basically, create your own DataAnnotation, which will pull the minimum length from web.config.

For posterity, here is the code used on the link site:

 [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) }; } } 

and on your 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; } 
+8
source

If you need variable parameters for your validation attributes, you would like to design your own attribute and apply it.

Perhaps call it "MinLengthFromConfigFile"?

+1
source

All Articles