How to validate PasswordBox WPF
See the question and my original answer on StackOverflowAnother solution, without using any "unsecure" string in the middle, is to adapt the Window code, something like this:
Let's suppose I have an MVVM object like this, with WPF validation using IDataErrorInfo:
public class MyObject : INotifyPropertyChanged, IDataErrorInfo
{
...
public SecureString SecurePassword
{
get
{ ... }
set
{
...
OnPropertyChanged("SecurePassword");
}
}
...
string IDataErrorInfo.Error { get { return Validate(null); } }
string IDataErrorInfo.this[string columnName] { get { return Validate(columnName); } }
private string Validate(string memberName)
{
string error = null;
...
if (memberName == "SecurePassword" || memberName == null)
{
// this is where I code my custom business rule
if (SecurePassword == null || SecurePassword.Length == 0)
{
error = "Password must be specified.";
}
}
...
return error;
}
}
And a Window Xaml with a PasswordBox like this:
<PasswordBox Name="MyPassword" PasswordChanged="MyPassword_Changed" ... />
Then, the corresponding Window code like this will trigger PasswordBox binding:
// add a custom DependencyProperty
public static readonly DependencyProperty SecurePasswordProperty =
DependencyProperty.RegisterAttached("SecurePassword", typeof(SecureString), typeof(MyWindow));
public MyWindow()
{
InitializeComponent();
DataContext = myObject; // created somewhere
// create a binding by code
Binding passwordBinding = new Binding(SecurePasswordProperty.Name);
passwordBinding.Source = myObject;
passwordBinding.ValidatesOnDataErrors = true;
// you can configure other binding stuff here
MyPassword.SetBinding(SecurePasswordProperty, passwordBinding);
}
private void MyPassword_Changed(object sender, RoutedEventArgs e)
{
// this should trigger binding and therefore validation
((MyObject)DataContext).SecurePassword = MyPassword.SecurePassword;
}