Mask A Phone Number In Xamarin.Forms Using Behaviors

Introduction

This article demonstrates how to mask phone number field like XXX-XXX-XXXX using the Xamarin Forms Behaviors concept.

Prerequisites

  • Windows or Mac machine
  • Visual Studio has to be installed in it
  • A virtual device or real device for both Android and iOS platforms to run and observe the application

The flow of the article

  • How to create a Xamarin Forms Project
  • What is Behavior?
  • How to create Behavior?
  • How to mask phone number using Behavior?

How to create a Xamarin Forms Project?

  • On the Start screen, launch Visual Studio. This opens the start page.

    Xamarin
  • In Visual Studio, click "Create new project..." to create a new project.
    Xamarin
  • In the New project window, click Cross-Platform from the left pane, select the Mobile App (Xamarin.Forms) template, set the Name and Solution name to PhoneNumberMask, choose a suitable location for the project, and click the OK button.

    Xamarin 
  • In the New Cross-Platform App dialog, click Blank App, select .NET Standard as the Code Sharing Strategy, and click the OK button.

    Xamarin
  • In Solution Explorer, the PhoneNumberMask project will be displayed like below.

    Xamarin

What is Behavior?

  • Behaviors allow us to add functionality to User Interface controls without creating the subclass for it. Instead, the functionality is implemented in behavior class and attached to the control.
  • Behaviors are written in the code and added to controls in XAML or code in the code behind page.

How to create Behavior?

The process of creating a Xamarin.Forms Behavior is as follows.

  • Create a class that inherits from the Behavior or Behavior<T> class, where T is the type of the control to which the behavior should apply.
  • Override the OnAttachedTo method to perform any required setup.
  • Override the OnDetachingFrom method to perform any required cleanup.
  • Implement the core functionality of the behavior.

Now, we will start creating a behavior for phone number masking.

  • Right-click on PCL/NET Standard (PhoneNumberMask) project and select Add and then click on Class, as shown in the below diagram.

    Xamarin
  • Then, the "Add New Item" window will open like below.

    Xamarin

In the above window, I have named a class “PhoneNumberMaskBehavior” and then clicked on Add button.

  • The class will be created as shown below.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Text;  
    4.   
    5. namespace PhoneNumberMask  
    6. {  
    7.     class PhoneNumberMaskBehavior  
    8.     {  
    9.     }  

Replace the above class with the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace PhoneNumberMask  
  7. {  
  8.     public class PhoneNumberMaskBehavior : Behavior<Entry>  
  9.     {  
  10.         public static PhoneNumberMaskBehavior Instance = new PhoneNumberMaskBehavior();  
  11.   
  12.         ///  
  13.         /// Attaches when the page is first created.  
  14.         ///   
  15.   
  16.         protected override void OnAttachedTo(Entry entry)  
  17.         {  
  18.             entry.TextChanged += OnEntryTextChanged;  
  19.             base.OnAttachedTo(entry);  
  20.         }  
  21.   
  22.         ///  
  23.         /// Detaches when the page is destroyed.  
  24.         ///   
  25.   
  26.         protected override void OnDetachingFrom(Entry entry)  
  27.         {  
  28.             entry.TextChanged -= OnEntryTextChanged;  
  29.             base.OnDetachingFrom(entry);  
  30.         }  
  31.   
  32.         private void OnEntryTextChanged(object sender, TextChangedEventArgs args)  
  33.         {  
  34.             if (!string.IsNullOrWhiteSpace(args.NewTextValue))  
  35.             {  
  36.                 // If the new value is longer than the old value, the user is  
  37.   if (args.OldTextValue != null && args.NewTextValue.Length <         args.OldTextValue.Length)  
  38.                     return;  
  39.   
  40.                 var value = args.NewTextValue;  
  41.   
  42.                 if (value.Length == 3)  
  43.                 {  
  44.                     ((Entry)sender).Text += "-";  
  45.                     return;  
  46.                 }  
  47.   
  48.                 if (value.Length == 7)  
  49.                 {  
  50.                     ((Entry)sender).Text += "-";  
  51.                     return;  
  52.                 }  
  53.   
  54.                 ((Entry)sender).Text = args.NewTextValue;  
  55.             }  
  56.         }  
  57.     }  
  58. }  
  • Similarly, create one more behavior to set Maximum length for phone number as below.
    1. using Xamarin.Forms;  
    2.   
    3. namespace PhoneNumberMask  
    4. {  
    5.     public class EntryLengthValidator : Behavior<Entry>  
    6.     {  
    7.         public int MaxLength { get; set; }  
    8.         public int MinLength { get; set; } = 0;  
    9.   
    10.         protected override void OnAttachedTo(Entry bindable)  
    11.         {  
    12.             base.OnAttachedTo(bindable);  
    13.             bindable.TextChanged += OnEntryTextChanged;  
    14.         }  
    15.   
    16.         protected override void OnDetachingFrom(Entry bindable)  
    17.         {  
    18.             base.OnDetachingFrom(bindable);  
    19.             bindable.TextChanged -= OnEntryTextChanged;  
    20.         }  
    21.   
    22.         void OnEntryTextChanged(object sender, TextChangedEventArgs e)  
    23.         {  
    24.             var entry = (Entry)sender;  
    25.   
    26.             // if Entry text is longer than valid length  
    27.             if (entry.Text.Length > this.MaxLength)  
    28.             {  
    29.                 string entryText = entry.Text;  
    30.   
    31.                 entryText = entryText.Remove(entryText.Length - 1); // remove last char  
    32.   
    33.                 entry.Text = entryText;  
    34.             }  
    35.   
    36.             if (MinLength > 0)  
    37.                 if (entry.Text.Length < this.MinLength)  
    38.                 {  
    39.                     ((Entry)sender).TextColor = Color.Red;  
    40.                 }  
    41.                 else  
    42.                     ((Entry)sender).TextColor = Color.Black;  
    43.         }  
    44.     }  
    45. }  
  • Open mainPage.xaml and paste the following code in it.
    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
    3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
    4.              xmlns:behavior="clr-namespace:PhoneNumberMask"  
    5.              x:Class="PhoneNumberMask.MainPage">  
    6.   
    7.     <StackLayout HorizontalOptions="Fill"  
    8.                  VerticalOptions="Fill"  
    9.                  Padding="5,20,5,5">  
    10.         <Label Text="Phone Number Formatting"  
    11.                FontAttributes="Bold"  
    12.                FontSize="Medium"></Label>  
    13.         <Entry Text="{Binding Phone}" Keyboard="Telephone">  
    14.             <Entry.Behaviors>  
    15.                 <behavior:PhoneNumberMaskBehavior x:Name="PhoneMask" />  
    16.           <behavior:EntryLengthValidator MaxLength="12"/>  
    17.             </Entry.Behaviors>  
    18.         </Entry>  
    19.     </StackLayout>  
    20. </ContentPage>  
  • Now, set either Android or iOS project as start-up project and run the application. You will see the output like below.

    Xamarin

    When I try to enter the phone number in Entry box shown in above screen, it has displayed like below.

    Xamarin

To view the full source code, please click here.

Summary

To display the phone number in XXX-XXX-XXXX format, I have used two behaviors for the Entry control defined in MainPage.xaml.

They are,

  • EntryLengthValidator
    To allow a maximum number of characters.

  • PhoneNumberMaskBehavior
    To mask the phone number in XXX-XXX-XXXX format

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now