Friday, September 29, 2017

Xamarin Forms Validation the easy way



Actually there is no easy way (forgive me), but this article will help you the right way of doing it. The main reason why we need an input validation is to ensure a right data will be entered in to our app and it also provide extra protection because it enforces business rule that no garbage data will be going into the system.


First you need to understand the basics of Behaviors,  it lets you add functionality to your UI controls without having to subclass them, a function like validating input, controlling animation, adding effects and triggering commands and making it reusable component,  In our case we will gonna use it to provide validation for our inputs. If you want to get started and get to know more about Behaviors you can start in this LINK.

Then we also need to add Triggers in our arsenal, Triggers allow your UI element to respond to any property changes in pure xaml (Yes you read it right), We will provide a sample later and dissect how Behaviors and triggers all work together to obtain our goal.






Reusability 



The Behaviors and Triggers are the components that can be made reusable across your app which makes validation and animation a breeze. This will also reduce backends extra checking and "if-else" (f*cking old fashion way).



Creating Your Xamarin.Forms project 



Now let us create our new project and name it "ValidationApp", you should be able to create three platforms project and atleast  one PCL project. We will reuse the default page and create a similar UI like the one below. we will make sure thats our xamarin.forms library are up to date by updating our nuget packages.







Select the Portable Class Library






Dissecting Behavior 



Behaviors is very much like our C# Extension methods but for xaml elements. Now lets methodically cut up a part of Behavior and study how it make sense. In this case i already created a Generic Behaviorbase. Now lets make a simple Behavior which will validate an empty text, Let's name it "EntryValidatorBehavior". It should look like the one below.

 



Now let us expose a bindable property which will notify our xaml element that the entry is valid, In Our case we will named it "IsValid, it should look like this:





The last but not the least let us subscribe to Entry's TextChanged event to listen when the user has entered a new value. We need to override two methods from a behavior namely "OnAttachedTo" and "OnDetachingFrom" and add a subscribe and unsubscribe to TextChanged event respectively. What you see is a complete version of our EntryValidatorBehavior.







Awesome! Let's see it in Action 


You just have created a "REUSABLE" component which can be used across your app UI "congratulations". Now, Let us use the default page "MainPage" to test our EntryValidatorBehavior, For simplicity sake we will only create one entry and one button, like the one below.





Our objective to make the user input a non-empty code before submitting it, In our case we will disable a button until he inputs a non-empty code.






Dissecting our XAML Code 



This is our XAML Code, i did make it simple as much as possible so we could get  a grasp of it. If you take a look of it it has one Entry and one Button, Everytime the user changes the value of the entry it will change the state of "IsValid" property in which will invoke  triggers which has a binding to its property.





Awesome, now lets try to run our app and see it in action. I you have run the app you will notice that when the entry's value is blank will disable the button or it will enable when the entry has non-empty value.






New Validation Plugin


Though behaviors may have done a great job with simple validation it cannot solve complex ones, So I recommend you a more versatile and unobstrusive validation that are more complex than this, You can use Matcha Validation [LINK]. 





Wrapping Up


Creating maintenable and reusable components is breeze when you will follow this patterns, And as your app is getting more complex you will appreciate the awesomeness of this patterns and leave you concentrating on the more important business aspects on your application. If you want more and advance topic you can catch us at this facebook groups  MondPH And Xamdavao.  If you want the full sample source you can check it right here LINK.






6 comments:

  1. Where to find xamarin developers - Inwizards is a Xamarin Development Company offers you to hire xamarin developers for xamarin mobile app development services.
    Xamarin services India
    xamarin development company

    ReplyDelete
  2. how can we validate multiple entries with button?

    ReplyDelete
    Replies
    1. Hi Dilip, You need to add more DataTrigger to Button, in our example we have only two(2), if you add another behavior to validate another input the DataTrigger would become Four. Hope it helps.

      Delete
    2. Hi Winston,
      Thanks for your sample. But what if I need to enable the button only when ALL of the multiple entries are not empty? Adding just more DataTrigger's won't do...

      Delete
    3. Hi, I hope your are doin fine, this approach is only for simple validation. If you want a more sophisticated approach of validation you can this link here https://winstongubantes.blogspot.com/2018/08/unobtrusive-validation-for-enterprise.html

      Delete
  3. Nice presentation Man. I like the trigger approach. and easy to add an effect too.

    ReplyDelete