Validation helpers for ReactiveUI-based apps.
Перейти к файлу
Artyom V. Gorchakov 4f61a89be2
Update links and code snippets in README.md (#84)
2020-07-19 05:27:56 +10:00
.github Housekeeping: add open collective bot configuration file 2019-04-01 11:05:15 -07:00
media Added logo. 2019-02-24 12:35:07 +01:00
samples/xamarin-forms/LoginApp Added an analyzers, support for multiple validation and added Xamarin.Forms sample. (#5) 2019-03-19 12:38:12 -07:00
src Fix #60, #61, #70 (#82) 2020-07-17 23:10:15 +10:00
.editorconfig housekeeping: Update to the latest msbuild.sdk.extras/pipelines 2019-08-06 04:05:58 +10:00
.gitattributes Added an analyzers, support for multiple validation and added Xamarin.Forms sample. (#5) 2019-03-19 12:38:12 -07:00
.gitignore housekeeping: Update to the latest msbuild.sdk.extras/pipelines 2019-08-06 04:05:58 +10:00
LICENSE Added an analyzers, support for multiple validation and added Xamarin.Forms sample. (#5) 2019-03-19 12:38:12 -07:00
README.md Update links and code snippets in README.md (#84) 2020-07-19 05:27:56 +10:00
analyzers.ruleset Added an analyzers, support for multiple validation and added Xamarin.Forms sample. (#5) 2019-03-19 12:38:12 -07:00
analyzers.tests.ruleset Added an analyzers, support for multiple validation and added Xamarin.Forms sample. (#5) 2019-03-19 12:38:12 -07:00
azure-pipelines.yml Update azure-pipelines.yml 2020-07-04 14:44:03 +10:00
build.cake housekeeping: Update cake/targets to latest (#43) 2019-09-21 13:08:12 +10:00
build.cmd housekeeping: Add android support/CI engine support 2019-02-26 01:08:42 -08:00
build.config housekeeping: Updated Cake to v0.38.1 (#78) 2020-06-09 13:37:45 +10:00
build.ps1 housekeeping: update cake to 0.33.0 2019-05-07 09:24:49 +10:00
build.sh housekeeping: Add android support/CI engine support 2019-02-26 01:08:42 -08:00
cake.config housekeeping: update cake to 0.33.0 2019-05-07 09:24:49 +10:00
version.json Update version.json (#83) 2020-07-18 10:59:30 +10:00

README.md

NuGet Stats Build Status Code Coverage #yourfirstpr Downloads Slack

ReactiveUI.Validation

Validation for ReactiveUI based solutions, functioning in a reactive way.

This repository is based on jcmm33's Vistian.Reactive.Validation.

NuGet Packages

Install the following package into you class library and platform-specific project. ReactiveUI.Validation package supports all platforms, including .NET Framework, .NET Standard, MonoAndroid, Tizen, UAP, Xamarin.iOS, Xamarin.Mac, Xamarin.TVOS.

Platform ReactiveUI Package NuGet
Any ReactiveUI.Validation CoreBadge

How to use

  • For ViewModels which need validation, implement IValidatableViewModel.
  • Add validation rules to the ViewModel.
  • Bind to the validation rules in the View.

Example

  1. Decorate existing ViewModel with IValidatableViewModel, which has a single member, ValidationContext. The ValidationContext contains all of the functionality surrounding the validation of the ViewModel. Most access to the specification of validation rules is performed through extension methods on the IValidatableViewModel interface. Then, add validation to the ViewModel.
public class SampleViewModel : ReactiveObject, IValidatableViewModel
{
    public SampleViewModel()
    {
        // Creates the validation for the Name property.
        this.ValidationRule(
            viewModel => viewModel.Name,
            name => !string.IsNullOrWhiteSpace(name),
            "You must specify a valid name");
    }

    public ValidationContext ValidationContext { get; } = new ValidationContext();

    private string _name;
    public string Name
    {
        get => _name;
        set => this.RaiseAndSetIfChanged(ref _name, value);
    }
}

For more complex validations there is also the possibility to supply an Observable<bool> indicating whether the rule is valid or not. Thus you can combine multiple properties or incorporate other complex logic.

this.ValidationRule(
    vm => vm.WhenAnyValue(x => x.TextInput1, x => x.TextInput2, (input1, input2) => input1 == input2)
    (vm, isValid) => isValid ? string.Empty : "Both inputs should be the same");
  1. Add validation presentation to the View.
public class SampleView : ReactiveContentPage<SampleViewModel>
{
    public SampleView()
    {
        InitializeComponent();
        this.WhenActivated(disposables =>
        {
            this.Bind(ViewModel, vm => vm.Name, view => view.Name.Text)
                .DisposeWith(disposables);

            // Bind any validations which reference the Name property 
            // to the text of the NameError UI control.
            this.BindValidation(ViewModel, vm => vm.Name, view => view.NameError.Text)
                .DisposeWith(disposables);
        });
    }
}

Note Name is an Entry and NameError is a Label (both are controls from the Xamarin.Forms library).

Example with Android extensions

There are extensions methods for Android specific and its Material design control TextInputLayout. These extensions use internally the Error property from this control, allowing you a Material Design and fully native behavior to showing errors.

To use these extensions you must import ReactiveUI.Validation.Platforms.Android.

using ReactiveUI.Validation.Platforms.Android;

namespace SampleApp.Activities
{
    public class SampleActivity : ReactiveAppCompatActivity<SampleViewModel>
    {
        public TextInputEditText Name { get; set; }

        public TextInputLayout NameLayout { get; set; }

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate(bundle);

            // Sets our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            WireUpControls();

            this.Bind(ViewModel, vm => vm.Name, view => view.Name.Text);

            // Bind any validations which reference the Name property 
            // to the Error property of the TextInputLayout control
            this.BindValidation(ViewModel, vm => vm.Name, NameLayout);
        }
    }
}

INotifyDataErrorInfo Support

For those platforms which support the INotifyDataErrorInfo interface, ReactiveUI.Validation provides a helper base class named ReactiveValidationObject<TViewModel>. The helper class implements both the IValidatableViewModel interface and the INotifyDataErrorInfo interface. It listens to any changes in the ValidationContext and invokes INotifyDataErrorInfo events.

public class SampleViewModel : ReactiveValidationObject<SampleViewModel>
{
    [Reactive]
    public string Name { get; set; } = string.Empty;

    public SampleViewModel()
    {
        this.ValidationRule(
            x => x.Name, 
            name => !string.IsNullOrWhiteSpace(name),
            "Name shouldn't be empty.");
    }
}

Note The Reactive attribute is from the ReactiveUI.Fody NuGet package.

When using the ValidationRule overload that uses Observable<bool> for more complex scenarios please keep in mind to supply the property which the validation rule is targeting as the first argument. Otherwise it is not possible for INotifyDataErrorInfo to conclude which property the error message is for.


this.ValidationRule(
    vm => vm.TextInput2,
    vm => vm.WhenAnyValue(x => x.TextInput1, x => x.TextInput2, (input1, input2) => input1 == input2)
    (vm, isValid) => isValid ? string.Empty : "Both inputs should be the same");

Capabilities

  1. Rules can be composed of single or multiple properties along with more generic Observables.
  2. Validation text can encapsulate both valid and invalid states.
  3. Binding can occur to either a View or an action.
  4. Validation text can reference either the ViewModel or properties which comprise the validation rule e.g. include text entered as part of validation message.
  5. Validation text output can be adjusted using custom formatters, not only allowing for single & multiline output but also for platforms like Android it should be possible to achieve richer renderings i.e. Bold/italics.

How it Works

In essence, it's a relatively simple model of the ValidationContext containing a list of IValidationComponent instances. An IValidationComponent provides an observable for ValidationState. Whenever validation state changes (either a transition of validity) or ValidationText changes, then a new value is pushed out.

Feedback

Please use GitHub issues for questions or comments.

Authors

Contribute

ReactiveUI.Validation is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Because of our Open Collective model for funding and transparency, we are able to funnel support and funds through to our contributors and community. We ❤ the people who are involved in this project, and wed love to have you on board, especially if you are just getting started or have never contributed to open-source before.

So here's to you, lovely person who wants to join us — this is how you can support us:

Code released under the MIT license.