It's good to clarify that this publication focuses on validating our model in Xamarin with the Plugin Plugin.ValidationRules. In the same way, you can see the examples with the approach used in this post.
Introduction - ValidationRules
Validating user input data with Plugin.ValidationRules is relatively easy. However, in the main documentation the examples are presented with the direct properties. You and I know that if we work in a structured way the normal thing is to have a model to map the data we will use in our application.
To illustrate this proposed context, it will be shown how easy it is to validate our model with Plugin.ValidationRules. Great, let's start!
The first thing would be to define your model and the properties that it is going to have. These properties must be a
Something evident that you can notice here, is that we are initializing our properties directly in the constructor of our model. Although, you can leave it like this or make your implementation in your ViewModel.
Note: Your properties don't need to implement the interface
INotifyPropertyChangedfor updating your UI. Plugin.ValidationRules has its own implementation called
ExtendedPropertyChanged. This means that the plugin does all the job for you.
At this point you can add the validations directly in your model to avoid duplicate code. Or you can do it in your ViewModel as shown below.
To validate a property, just call the myProperty.Validate() method.
EXTRA: You can also add an EventToCommandBehavior and bind it to a command that call the validate method.
To bind your properties and errors to your XAML file; do it in the following way.
Plugin.ValidationRules is the easy way to add client-side validation of view model properties. Notifies the user of any validation errors by showing them the control that contains the invalid data.
- Official documentation: Validation Rules for Xamarin and Windows
- Available on NuGet: Plugin.
- Repository: Validation Rules Plugin for Xamarin and Windows
- Examples: Repository
- Extension for Visual Studio: Validation Rule Template
- How to use Validation Rule Template
- More resources: Xamarin Universal Library
Thank you somuch for reading this post!