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.
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
Shell, Visual y CollectionView are the new feature...
Microsoft Learn, the new Microsoft learning platfo...
As 2018 comes to an end, we are ready for this 201...
Opportunity to learn to develop mobile application...
I invite you to see my opinion on whether “I...
I invite you to see my opinion on this topic and t...
I’m Luis Matos from the Dominican Republic. I have +5 years working with .Net and +3 with Xamarin. Currently, I’m a Xamarin Certified Developer.
I invite you to leave me your feedback about this post in the comment box. If you want me to talk about a specific topic or detail a few more topics, let me know. The most interesting topics will be added to my list of future posts.