7

I am trying to add validation on a text for required field using the "ValidationRule" class. I have the following implementation of the class

using System.Windows.Controls;
using System.Globalization;

public class RequiredField : ValidationRule
{
    private String _errorMessage = String.Empty;
    public string ErrorMessage
    {
        get { return _errorMessage; }
        set { _errorMessage = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var str = value as string;

        if (String.IsNullOrEmpty(str))
        {
            return new ValidationResult(true, this.ErrorMessage);
        }

        return new ValidationResult(true, null);
    }
}

Further in my XAML, i have the following implementation of it:

      <TextBox Grid.Row="1" Grid.Column="3"  Name="txtUserName"  Height="23" VerticalAlignment="Top" Width="70" Grid.ColumnSpan="2" HorizontalAlignment="Left" MaxLength="50">
        <TextBox.Text>
            <Binding Path="Username" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <validators:RequiredField ErrorMessage="username is required." />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>

    </TextBox>

and for displaying the error message, i have the following error template style in app.xaml

            <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">

                            <TextBlock DockPanel.Dock="Right"
                            Foreground="Orange"
                            Margin="5" 
                            FontSize="12pt"
                            Text="{Binding ElementName=MyAdorner, 
                           Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                            </TextBlock>

                            <Border BorderBrush="Green" BorderThickness="3">
                                <AdornedElementPlaceholder Name="MyAdorner" />
                            </Border>

                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
                    Value="{Binding RelativeSource={RelativeSource Self}, 
                   Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

The code is compiling and running fine. Even the validationRule method is getting hit by the debugger. But the issue is that the message for error is not getting displayed.

I have attached the Model using the following code :

 ApplicationUsersUIContract ss = new ApplicationUsersUIContract();
                         this.DataContext = ss;

I am new to the concept of WPF. What am i missing here ? Any help is greatly appreciated.

Tech Jay
  • 404
  • 1
  • 6
  • 16

1 Answers1

1

Everything is perfect except you are passing isValid to true even in case of validation failure -

    if (String.IsNullOrEmpty(str))
    {
        return new ValidationResult(true, this.ErrorMessage); <--- HERE        
    }

It should be false instead -

return new ValidationResult(false, this.ErrorMessage);
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 1
    Oopppsss...!!! u were correct Rohit. Atleast it will help others now to implement the validations...thanks for that... – Tech Jay Sep 21 '13 at 09:47
  • How can I use this for the Password type Box ? It gives the following error : A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. – Tech Jay Sep 21 '13 at 11:12
  • That's true `Password` is not DP in passwordBox. You can't bind with it ofcourse because of security reasons. – Rohit Vats Sep 21 '13 at 12:16
  • Refer to the link here - http://stackoverflow.com/questions/1483892/how-to-bind-to-a-passwordbox-in-mvvm – Rohit Vats Sep 21 '13 at 12:17
  • Yes i googled and found the same reason. Also got the concept of Attached properties like the link below. But i am not sure how i can use this along with the one i applied on normal textbox http://wpftutorial.net/PasswordBox.html Can you suggest some change in the existing code and integrate with the above solution...??? – Tech Jay Sep 21 '13 at 15:40