diff --git a/docs/concepts/reactiveui/reactive-view-model.md b/docs/concepts/reactiveui/reactive-view-model.md index 097b3a841..db5b5f93d 100644 --- a/docs/concepts/reactiveui/reactive-view-model.md +++ b/docs/concepts/reactiveui/reactive-view-model.md @@ -59,3 +59,65 @@ Any change to the view model description property is achieved using the `set` ac When _Avalonia UI_ uses the binding to **Update** the view model, the `set` accessor ensures that any parts of the view model that depend on the description property can also react to the change if necessary. On the next page, you will learn how a reactive command acts as a special case of the view model update. + +## Performing Data Validation +ReactiveUI provides the ability to perform data validation from the ViewModel that integrates well with the Avalonia fluent controls. The example shows how this can be done. The example is for a ViewModel that exposes a directory path string that is bounded to a TextBox control on the View. + +Steps to enable data validation on the ViewModel: +1. Download the ReactiveUI.Validation nuget package (for desktop applications) +2. Change the inheritance of the ViewModel to ReactiveValidationObject +3. Include a this.ValidationRule in the ViewModel constructor, which provides the validation check for the ViewModel property and corresponding validation error message. + +The code below shows the MainWindowViewModel.cs and MainWindow.axaml +```C# +using System.IO; +using ReactiveUI; +using ReactiveUI.Validation.Extensions; +using ReactiveUI.Validation.Helpers; + +namespace AvaloniaApplication3.ViewModels; + +public class MainWindowViewModel : ReactiveValidationObject +{ + private string _directoryPath = string.Empty; + + public string DirectoryPath + { + get => _directoryPath; + set => this.RaiseAndSetIfChanged(ref _directoryPath, value); + } + + public MainWindowViewModel() + { + DirectoryPath = "C:\\BogusPath\\"; + this.ValidationRule( + vm => vm.DirectoryPath, + path => Directory.Exists(path), + "You must specify a valid directory path."); + + } +} +``` +```xaml + + + + + +``` +Below is the output: + +![Avalonia-ReactiveUI-DataValidation](https://github.com/AvaloniaUI/avalonia-docs/assets/130417839/75aede6b-f8cc-4bb8-8520-f9a8f24aa779)