Wednesday, March 30, 2016

Xamarin.Forms validation using Behaviors

I''m starting with Xamarin not long time ago. Facing with validation problem, I found very useful class Behaviors. It's not all about validation but also can do more cool things with this class. In this post, I will focus on my way to use it in validation for client side.

The first thing, maybe you should look at this post:
https://blog.xamarin.com/behaviors-in-xamarin-forms/

Base on this, I do some changing code.
- In the real thing, you may like to validate many condition for one controls (such as: Require and email format, require and maxlength...). To make it easier I create validation class to validate for each control type, instead of each rule. Let's see the code is changed:

* Note: It's contain some constants and reference to my source code so if you just copy&paste, it will not work, let's try to understand it.

Some thing changed here:
- The first thing I add Message property to provide different validate message of each error for client to display. You see I set value for the Message in HandleTextChanged method.
- Each kind of validate will have an option to validate it or not. In my code you will see: IsCheckEmpty, IsCheckEmail that you can control what you wanna validate for Entry or not.
- The HandleTextChanged method ( or handle another event) will do validate and set value for IsValid and Message. You may wonder what is ValidatorsFactory, that the logic of validate I moved to other class call ValidatorsFactory.