Xamarin Forms – Creating Behaviors for Validation

In this post we will create Xamarin forms behaviors.

Behaviors in Xamarin forms ables us to add functionality to user interface without having to subclass them. In xamarin forms Behaviors are created by deriving Behavior<T> class where <T> is user control element (Example: Entry).

To use it, we have to override two methods OnAttachedTo and OnDetachingFrom methods from Behavior class. So let’s implement it.

DOWNLOAD SOURCE CODE

In your Xamarin form project create a folder named “Behaviors” and add following classes with its code.

The first one is for checking if the user has entered a double value in the Entry.

DoubleEntry.cs:

using Xamarin.Forms;

namespace XamBehaviours.Behaviours
{
public class DoubleEntry : Behavior<Entry>
{
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnTextChanged;
base.OnAttachedTo(entry);
}

protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnTextChanged;
base.OnDetachingFrom(entry);
}

private void OnTextChanged(object sender, TextChangedEventArgs e)
{
double result;
bool isValid = double.TryParse(e.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.FromHex("#000") : Color.FromHex("#ff9c96");
}
}
}

Second is NumericEntry. It will check whether the user as entered integer value or not. It will also validate double value.

NumericEntry.cs:

using Xamarin.Forms;

namespace XamBehaviours.Behaviours
{
public class NumericEntry : Behavior<Entry>
{

protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnTextChanged;
base.OnAttachedTo(entry);
}

protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnTextChanged;
base.OnDetachingFrom(entry);
}

private void OnTextChanged(object sender, TextChangedEventArgs e)
{
int result;
bool isValid = int.TryParse(e.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.FromHex("#000") : Color.FromHex("#ff9c96");
}
}
}

Third is EmailEntry. This behavior class can be used for validating user’s entry for Email validation.

EmailEntry.cs:

using System.Text.RegularExpressions;
using Xamarin.Forms;

namespace XamBehaviours.Behaviours
{
public class EmailEntry : Behavior<Entry>
{
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnTextChanged;
base.OnAttachedTo(entry);
}

protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnTextChanged;
base.OnDetachingFrom(entry);
}

private void OnTextChanged(object sender, TextChangedEventArgs e)
{
var emailPattern = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))"
+ @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";

((Entry)sender).TextColor = Regex.IsMatch(e.NewTextValue,emailPattern) ?
Color.FromHex("#000") : Color.FromHex("#ff9c96");
}
}
}

The last one is MaxLengthValidation. This behavior is useful for validating max number of character entered in a entry. Example when you want user to enter a mobile number, if in your country max length of a mobile number is 10, you can validate if it exceeds 10 characters.

MaxLengthValidator.cs:

using Xamarin.Forms;

namespace XamBehaviours.Behaviours
{
public class MaxLengthValidator : Behavior<Entry>
{
public static BindableProperty maxLength =
BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator),0);

public int MaxLength
{
get { return (int)GetValue(maxLength); }
set { SetValue(maxLength, value); }
}

protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnTextChanged;
}

protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnTextChanged;
}

private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Length > MaxLength)
((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength);
}

}
}

Now let’s implement our behavior classes in layout files and use it.

Create a new ContentPage with name MainPage.xaml and edit it as below:

MainPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamBehaviours.Behaviours"
Title="Behaviors in Xamarin.Forms"
x:Class="XamBehaviours.MainPage">

<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

<Entry Placeholder="Enter Only Numbers" Margin="5" Keyboard="Numeric">
<Entry.Behaviors>
<local:NumericEntry/>
</Entry.Behaviors>
</Entry>

<Entry Placeholder="Enter Double Value" Margin="5" Keyboard="Numeric">
<Entry.Behaviors>
<local:DoubleEntry/>
</Entry.Behaviors>
</Entry>

<Entry Placeholder="Enter Email Address" Margin="5" Keyboard="Email">
<Entry.Behaviors>
<local:EmailEntry/>
</Entry.Behaviors>
</Entry>

<Entry Placeholder="Enter your Mobile Number" Margin="5" Keyboard="Numeric">
<Entry.Behaviors>
<local:MaxLengthValidator MaxLength="10"/>
</Entry.Behaviors>
</Entry>

</StackLayout>

</ContentPage>

Now let’s test our application:

DOWNLOAD SOURCE CODE