Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parameter for StringLength attribute

The code which is generally generated for a ASP.NET MVC 3 Membership, escpecially the property NewPassword of the class ChangePasswordModel looks roughly like:

    [Required]
    [StringLength(100, MinimumLength=6)]
    [DataType(DataType.Password)]
    [Display("Name = CurrentPassword")]
    public string NewPassword { get; set; }

In order to to fill some information with external parameters I am using RecourceType:
(In this case I am changing OldPassword and fill the attribute Display with some additional Data from a Resource

    [Required]
    [DataType(DataType.Password)]
    [Display(ResourceType = typeof(Account), Name = "ChangePasswordCurrent")]
    public string OldPassword { get; set; }

Back to NewPassword. How can I substitute the MinimumLenght with Membership.MinRequiredPasswordLength? : My attempt:

    [Required]
    [StringLength(100, MinimumLength=Membership.MinRequiredPasswordLength)] 
    [DataType(DataType.Password)]
    [Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
    public string NewPassword { get; set; }

This produces the error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type (http://msdn.microsoft.com/de-de/library/09ze6t76%28v=vs.90%29.aspx)

like image 770
Niklas S. Avatar asked Aug 28 '13 12:08

Niklas S.


1 Answers

Validation attributes must be compiled constants (like your error message states). You could create you own ValidationAttribute that handles this minimum length for you.

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

Then your view model could look like this (you could even get more fancy and add the max length part of your DataAnnotations in the ValidatePasswordLength attribute to remove that line)

[Required]
[StringLength(100)] 
[DataType(DataType.Password)]
[Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
[ValidatePasswordLength]
public string NewPassword { get; set; }
like image 54
Tommy Avatar answered Oct 03 '22 11:10

Tommy