Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate PasswordBox WPF

Tags:

c#

validation

wpf

I'm trying to make a validation for a PasswordBox. For making validations I followed this link, that shows how to validate on TextBox.

The problem comes with PasswordBoxes. Because its Password is not bindable due to security reasons, I tried to make a binding following this link (also explained here, for CodeProject users).

So, apparently, fantastic! I can bind my PasswordBox with its Password property, so then I can bind with my validation. But it ignores me...

This is a regular TextBox that I use and works fine:

<local:ErrorProvider Grid.Column="1" Grid.Row="2" >
    <TextBox Width="160" 
          HorizontalAlignment="Left" 
           Name="textBoxUserPass" 
           Text="{Binding Path=Password, UpdateSourceTrigger=Explicit}" />
 </local:ErrorProvider>

And this is the PasswordBox I tried to simulate:

<local:ErrorProvider Grid.Column="1" Grid.Row="2" >
      <PasswordBox Width="160"
          HorizontalAlignment="Left"
          Name="textBoxUserPass"
          local:PasswordBoxAssistant.BindPassword="True"
          local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password, UpdateSourceTrigger=Explicit}" />
 </local:ErrorProvider>

This is how I get the BindingExpression for each TextBox:

BindingExpression beUserName = textBoxUserName.GetBindingExpression(TextBox.TextProperty);
if (beUserName != null) beUserName.UpdateSource();

And this is how I get it for the PasswordBox:

BindingExpression bePassword = textBoxUserPass.GetBindingExpression(PasswordBoxAssistant.BoundPassword);
if (bePassword != null) bePassword.UpdateSource();

If we made any mistake (defined on my Validation class), when I do this:

if (!beUserName.HasError && !bePassword.HasError)

each BindingExpression should say true of false depending on error validations. But for my PasswordBox never gets the value... Any idea?

like image 312
Sonhja Avatar asked Feb 27 '13 12:02

Sonhja


3 Answers

As far as I remember, the only way to add validation on a PasswordBox is to throw a new ValidationException in the setter of the binding property for SecurePassword. The PasswordBoxAssistant will not help you with this.

like image 200
Cristian Chereches Avatar answered Nov 17 '22 21:11

Cristian Chereches


Try setting ValidatesOnDataErrors=True and ValidatesOnExceptions=True on your binding:

<PasswordBox ...
   local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password,
      UpdateSourceTrigger=Explicit, 
      ValidatesOnDataErrors=True, 
      ValidatesOnExceptions=True}"
/>
like image 33
Richard Deeming Avatar answered Nov 17 '22 22:11

Richard Deeming


Set Mode=TwoWay on your binding

local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password,Mode=TwoWay,
UpdateSourceTrigger=Explicit}"
like image 3
KevinChuelo Avatar answered Nov 17 '22 22:11

KevinChuelo