-3

How to do text box input validation in wpf MVVM structure?

Aftab Lala
  • 136
  • 6
  • There's lots of good information here: https://stackoverflow.com/questions/19539492/wpf-textbox-validation-c-sharp/37255232#37255232 - I found that implementing INotifyDataErrorInfo worked best for me. – Robin Bennett Sep 17 '18 at 08:04
  • I've got a great blog post [*Taking data binding, validation and MVVM to the next level*](http://techfilth.blogspot.com/2011/07/taking-databinding-validation-and-mvvm.html) that tells you exactly how to do that in an MVVM compliant way. – slugster Sep 17 '18 at 12:40

2 Answers2

1

You should implement the INotifyDataErrorInfo interface in your view model:

public class ViewModel : INotifyDataErrorInfo
{
    private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();

    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            //validate:
            if (_text?.Length < 3)
                _validationErrors[nameof(Text)] = "Too short...";
            ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
        }
    }

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    public bool HasErrors => _validationErrors.Count > 0;
    public IEnumerable GetErrors(string propertyName) =>
        _validationErrors.TryGetValue(propertyName, out string error) ? new string[1] { error } : null;
}

View:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>
mm8
  • 163,881
  • 10
  • 57
  • 88
0

check this: https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-binding-validation and consider on this: Validation.ErrorTemplate="{StaticResource validationTemplate}"

Ilya Grigoryan
  • 229
  • 1
  • 5