Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate password length using an attribute that also accepts empty?

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; }
}
like image 223
Carl R Avatar asked Aug 05 '26 23:08

Carl R


1 Answers

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);
}
like image 139
Julien Lebosquain Avatar answered Aug 08 '26 17:08

Julien Lebosquain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!