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