8

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.

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Oopppsss...!!! u were correct Rohit. Atleast it will help others now to implement the validations...thanks for that...
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.
That's true Password is not DP in passwordBox. You can't bind with it ofcourse because of security reasons.
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 wpftutorial.net/PasswordBox.html Can you suggest some change in the existing code and integrate with the above solution...???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.