-
Notifications
You must be signed in to change notification settings - Fork 11
Avalonia. Quick start
Install-Package ReactiveValidation.Avalonia
using ReactiveValidation;
public class YourViewModel : ValidatableObject
{ ... }
You also can use your base class, but you should inherit it from IValidatableObject
. You can read about it here.
Create ValidationBuilder<>
to begin creating validation rules. After all rules are specified, call Build(this)
and set result to Validator
property.
public class YourViewModel : ValidatableObject
{
public BaseSampleViewModel()
{
Validator = GetValidator();
}
private IObjectValidator GetValidator()
{
var builder = new ValidationBuilder<YourViewModel>();
builder.RuleFor(vm => vm.Name)
.NotEmpty()
.MaxLength(16)
.NotEqual("foo");
builder.RuleFor(vm => vm.Surname)
.Equal("foo");
builder.RuleFor(vm => vm.PhoneNumber)
.NotEmpty()
.Matches(@"^\d{9,12}$");
return builder.Build(this);
}
// Properties with realization INotifyPropertyChanged goes here.
}
If you want to specify rules in separate class, read about separate validation classes and validator factory.
Bind your View
and ViewModel
:
public partial class YourView : UserControl
{
public BaseSampleView()
{
DataContext = new YourViewModel();
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
At YourView.axaml
bind your properties inside it:
<Grid RowDefinitions="Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*,Auto">
<TextBlock Grid.Row="0" Grid.Column="0" Margin="3" Text="Name: " />
<TextBox Grid.Row="0" Grid.Column="1"
Text="{Binding Name, Mode=TwoWay}" />
<TextBlock Grid.Row="0" Grid.Column="2" Margin="3" MaxWidth="150" TextWrapping="Wrap"
Text="Name not empty, not equal 'foo' and max length is 16" />
<TextBlock Grid.Row="1" Grid.Column="0" Margin="3" Text="Surname: " />
<TextBox Grid.Row="1" Grid.Column="1"
Text="{Binding Surname, Mode=TwoWay}" />
<TextBlock Grid.Row="1" Grid.Column="2" Margin="3" MaxWidth="150" TextWrapping="Wrap"
Text="Surname should be equal 'foo'" />
<TextBlock Grid.Row="2" Grid.Column="0" Margin="3" Text="Phone number: " />
<TextBox Grid.Row="2" Grid.Column="1"
Text="{Binding PhoneNumber, Mode=TwoWay}" />
<TextBlock Grid.Row="2" Grid.Column="2" Margin="3" MaxWidth="150" TextWrapping="Wrap"
Text="Phone number required and allow from 9 to 12 digits" />
</Grid>
All properties are invalid:
All properties are valid:
If you want to use Warning
messages or run-time localization, you can override default theme. You can read about it here.
You also can check project with samples of using ReactiveValidation. Project located here.