user735052
user735052

Reputation: 33

WPF Validation Control

I am new to WPF and trying to implement validation control on submit form.

Can anyone help me. My code doen't show up any error message even if I enter invalid data infect it does nothing.

Here is my code,

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}


public class UserName : INotifyPropertyChanged, IDataErrorInfo
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }

    private string username;
    public string _UserName
    {
        get { return username; }
        set
        {
            username = value;
            OnPropertyChanged(new PropertyChangedEventArgs("_UserName"));
        }
    }
    public string this[string propertyName]
    {
        get
        {
            if (propertyName == "_UserName")
            {
                bool valid = true;
                foreach (char c in _UserName)
                {
                    if (!Char.IsLetterOrDigit(c))
                    {
                        valid = false;
                        break;
                    }
                }
                if (!valid)
                    return "The Username can only contain letters and numbers.";
            }
            return null;
        }
    }
    public string Error
    {
        get { return null; }
    }
}

} My XAML code is,

<Grid>
    <Label Content="User Name" Height="28" HorizontalAlignment="Left" Margin="27,37,0,0" Name="UserNameLB" VerticalAlignment="Top" Width="96" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="135,37,0,0" Name="UserNameTB" VerticalAlignment="Top" Width="189">
        <TextBox.Text>
            <Binding Path="_UserName">
                <Binding.ValidationRules>
                    <DataErrorValidationRule></DataErrorValidationRule>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

</Grid>

Upvotes: 2

Views: 4242

Answers (2)

All you need is to put all logic about your validation in a separate class that inherits from class ValidationRule and override method Validate. Then you can set the message you want to see about the reason of validation failure, like:

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
    try
    {
        if (!Char.IsLetterOrDigit(c))
        {
           return new ValidationResult(false,
                                       "The Username can only contain letters and numbers.");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
    catch (Exception e)
    {
        return new ValidationResult(false, "Illegal characters or " + e.Message);
    }
}

Upvotes: 1

Jake Berger
Jake Berger

Reputation: 5357

Try this:

EDIT: (here's a style I define which shows errors for all TextBox controls) (put it in Window.Resources)

This style will then show the error message in a ToolTip

<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip"
                    Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                    Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>
</Style>

<Grid>
    <Label Content="User Name" Height="28" HorizontalAlignment="Left" Margin="27,37,0,0" Name="UserNameLB" VerticalAlignment="Top" Width="96" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="135,37,0,0" 
             Name="UserNameTB" VerticalAlignment="Top" Width="189"
             Text={Binding Path=_UserName, UpdateSourceTrigger=LostFocus, 
                   ValidatesOnDataErrors=true, NotifyOnValidationError=true} />    
</Grid>

Source

Upvotes: 0

Related Questions