ValidationRules – Validating Our Model on Xamarin and Windows

If you don’t know how to use the Plugin.ValidationRules, I recommend you to see the main documentation. Well, once you know the plugin, we can continue to the next level.

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!

Implementation

Model

The first thing would be to define your model and the properties that it is going to have. These properties must be a ValidatableObject<T>.

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 INotifyPropertyChanged for updating your UI. Plugin.ValidationRules has its own implementation called ExtendedPropertyChanged. This means that the plugin does all the job for you.

Adding Validations

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.

Validating properties

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.

Displaying results

To bind your properties and errors to your XAML file; do it in the following way.

Final result

Conclusion

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.

Recursos

Thank you somuch for reading this post! 
ValidationRules – Validating Our Model on Xamarin and Windows
5 (100%) 1 vote

Others

feedback

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.

Do you like posts like this? Then, subscribe  and activate push notifications to receive updates. See you next time!

2019-06-01T07:05:23-04:00

Leave me your comments

avatar
  Subscribe  
Notify of