karl.r
karl.r

Reputation: 971

WPF PasswordBox validation

I'm trying to add some validation rules to 2 PasswordBoxes. Both must have more than 5 characters and, both passwords must match. I'm not currently using MVVM.

I figure I could check the password on the PasswordChanged event but I can't get the Invalid state to toggle on the boxes.

Does anyone have examples of something like this working?

Upvotes: 0

Views: 2315

Answers (1)

epxp
epxp

Reputation: 26

If I'm understanding this correctly, all you need is this code within the PasswordChanged event of the second PasswordBox:

    private void passwordBox2_PasswordChanged(object sender, RoutedEventArgs e)
    {
         if (passwordBox2.Password != passwordBox1.Password)
         {
             //Execute code to alert user passwords don't match here.
             passwordBox2.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
         }
         else
         {
             /*You must make sure that whatever you do is reversed here;
              *all users will get the above "error" whilst typing in and you need to make sure
              *that it goes when they're right!*/
             passwordBox2.Background = new SolidColorBrush(Color.FromArgb(255,0,0,0));
          }
    }

Upvotes: 1

Related Questions