Validate password length using an attribute that also accepts empty?

7.1k views Asked by At

I would like to validate password length on edit if password is entered otherwise empty should be considered ok.

I have seen suggestions to skip the attribute for the password in the edit model and do the validation in the code, but I want to use attributes for all validation.

It seems like there should be something like this already in the library. Have I simply missed it?
I'm using EntLib 5 VAB and MVC 2 on AspNet 3.5.

Vanilla edit model:

[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
public class EditAccountModel
{
    public Guid ProviderUserKey { get; set; }

    [Required]
    [DisplayName("User name")]
    public string UserName { get; set; }

    [Required]
    [Email(ErrorMessage = "Not a valid email")]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email address")]
    public string Email { get; set; }

    //[ValidatePasswordLength] <- Requires password
    [DataType(DataType.Password)]
    [DisplayName("Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [DisplayName("Confirm password")]
    public string ConfirmPassword { get; set; }
}
3

There are 3 answers

0
Julien Lebosquain On BEST ANSWER

ValidatePasswordLengthAttribute is not part of the MVC core, but is created within your project from the default MVC project template, in AccountModels.cs. You can freely modify its implementation. Change the IsValid method to accept null and the empty string as valid values.

public override bool IsValid(object value) {
    string valueAsString = value as string;
    return String.IsNullOrEmpty(valueAsString) || valueAsString.Length >= _minCharacters);
}
0
Peyman On

You can create new custom validation attribute.

Public Class MyCustomValidation : RegularExpressionAttribute
{
   public MyCustomValidation() : base([Your regular expression])
   {} 
}

And modify your code as below:

[MyCustomValidation(ErrorMessage = "")]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
0
Sundara Prabu On

This works with MVC4 and jQuery 1.8.

Requirement is Minimum 9 chars length, 1 special char and 1 digit and 1 Uppercase letter is mandatory in the password.

[DisplayName("Password")]
[RegularExpression(@"^.*(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*\(\)_\-+=]).*$", ErrorMessage = "User_Password_Expression")]
[StringLength(20, MinimumLength = 9,  ErrorMessage = "length err")]
[DataType(DataType.Password)]
public override sealed string Password { get; set; }