Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a View this is accessible using the @Membership component

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

However if you look at the default model in the example MVC Application 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 part I am curious about is the MinimumLength = 6 since this is hard coded it would mean that if I ever wanted to update the password length, I'd not only have to edit the web.config (like Microsoft suggest) but also search any references to it in the source and change all over the place (probably not the best programming practise).

Is there any ways of using variables in Attributes. I suspect not since this probably happens at compile time rather than runtime. If there isn't does anyone know of a better pattern to stop me having to find replace all references in the future?

like image 973
John Mitchell Avatar asked Jan 16 '23 07:01

John Mitchell


2 Answers

Here is an article that can help you answer you questions. Basically, create your own DataAnnotation that pulls the minimum length from the web.config.

For posterity, here is the code used in the referenced 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; }
like image 160
Tommy Avatar answered Jan 20 '23 15:01

Tommy


If you want variable parameters to your Validation attributes, you would want to develop your own attribute and apply it.

Perhaps call it "MinLengthFromConfigFile"?

like image 21
hometoast Avatar answered Jan 20 '23 15:01

hometoast