Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF validation using ValidationRule class

Tags:

wpf

xaml

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.

like image 942
Tech Jay Avatar asked Sep 21 '13 07:09

Tech Jay


1 Answers

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);
like image 150
Rohit Vats Avatar answered Oct 27 '22 14:10

Rohit Vats