Search code examples
asp.net-mvcasp.net-mvc-4data-annotationsminimumstring-length

DataAnnotations StringLength Attribute MVC - without max value


I am using Data Annotations for Model validation in MVC4 and am currently using the StringLengthAttribute however i do NOT want to specify a maximum value (currently set at 50) but DO want to specify a minimum string length value.

Is there a way to only specify only a minimum length? Perhaps another attribute i can use?

My current code is:

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Confirm New Password")]
    [StringLength(50, MinimumLength = 7)]
    [CompareAttribute("NewPassword", ErrorMessage = "The New Password and Confirm New Password fields did not match.")]
    public string ConfirmNewPassword { get; set; }

Solution

  • Is there a way to only specify only a minimum length? Perhaps another attribute i can use?

    Using the standard data annotation, No. You must specify the MaximumLength. Only the other parameters are optional.

    In such a case, I'd recommend something like this:

    [StringLength(int.MaxValue, MinimumLength = 7)]
    

    You can also use a Regex (regular expression) attribute like this one:

    [RegularExpression(@"^(?:.*[a-z]){7,}$", ErrorMessage = "String length must be greater than or equal 7 characters.")]
    

    More on this here: Password Strength Validation with Regular Expressions