Validate Entries using behaviours

This is based on a post here which is a little incomplete and had a couple of errors and some omissions.

The following example shows how to validate that an email address is valid

Create a new class that inherits from Behavior<T>. Make sure you don’t just inherit from Behavior as the code sample shows.

I used this, place in a folder and namespace of Behaviours (British English spelling!)

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

namespace MyApp.Behaviours

public class EmailValidatorBehavior : Behavior<Entry>
    const string emailRegex = @"^(?("")("".+?(?&lt;!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&lt;=[0-9a-z])@))" +

    static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(EmailValidatorBehavior), false);

    public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;

    protected override void OnAttachedTo(Entry bindable)
        bindable.TextChanged += HandleTextChanged;

    protected override void OnDetachingFrom(Entry bindable)
        bindable.TextChanged -= HandleTextChanged;

    public bool IsValid
        get { return (bool)base.GetValue(IsValidProperty); }
        private set { base.SetValue(IsValidPropertyKey, value); }

    void HandleTextChanged(object sender, TextChangedEventArgs e)
        IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
        ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;


In the view add an xmlns for this namespace


Then assuming you have an Entry for email already, then extend it to

<Entry Placeholder="Email" Keyboard="Email" Text="{Binding Email}">
                        <behaviours:EmailValidatorBehavior x:Name="emailValidator"/>

This makes a reference to the behaviour. Now when the Entry doesn’t contain a valid email the colour of the text in the Entry will change to red.

Now if you want to make this a bit clearer and place a label on the page that will say if the email is valid or not.

Add a label to the view.

<Label Style="{Binding Source={x:Reference emailValidator}, Path=IsValid, Converter={StaticResource boolToStyleEmail}}" />

The Binding Source={x:Reference emailValidator} says to bind with an element that’s on the view already. The Path bit determines the property to bind to.
The converter we’ll get onto next.
What this does is take the boolean IsValid property and convert it into a Style. It seems a Style can amend text as well as formatting.

I placed the code into a folder/namespace of Classes, so I needed another xmlns in my view.


And the following 2 Style to flip between.

            <Style x:Key="baseStyle" TargetType="Label">
                <Setter Property="HorizontalTextAlignment" Value="Start" />
                <Setter Property="FontSize" Value="Micro" />
                <Setter Property="FontAttributes" Value="Italic" />

            <classes:BooleanToObjectConverter x:Key="boolToStyleEmail" x:TypeArguments="Style">
                    <Style TargetType="Label" BasedOn="{StaticResource baseStyle}">
                        <Setter Property="TextColor" Value="#F44336" />
                        <Setter Property="Text" Value="Enter a valid email" />


                   <Style TargetType="Label" BasedOn="{StaticResource baseStyle}">
                        <Setter Property="TextColor" Value="#4CAF50" />
                        <Setter Property="Text" Value="Your email looks good" />



Note that this must be placed within the ContentPage.Resources / ResourceDictionary. I failed to do this and had troubles running the app on my device.

The code that changes a boolean to objects is

namespace MyApp.Classes
  public   class BooleanToObjectConverter<T> : IValueConverter
        public T FalseObject { set; get; }

        public T TrueObject { set; get; }

        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture)
            return (bool)value ? this.TrueObject : this.FalseObject;

        public object ConvertBack(object value, Type targetType,
                                  object parameter, CultureInfo culture)
            return ((T)value).Equals(this.TrueObject);

See this post on how I disable a button until the entries pass validation.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.