Introduction

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

Prerequisites

The flow of the article

How to create a Xamarin Forms Project?

What is Behavior?

How to create Behavior?

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

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

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

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. namespace PhoneNumberMask
  6. {
  7. public class PhoneNumberMaskBehavior : Behavior<Entry>
  8. {
  9. public static PhoneNumberMaskBehavior Instance = new PhoneNumberMaskBehavior();
  10. ///
  11. /// Attaches when the page is first created.
  12. ///
  13. protected override void OnAttachedTo(Entry entry)
  14. {
  15. entry.TextChanged += OnEntryTextChanged;
  16. base.OnAttachedTo(entry);
  17. }
  18. ///
  19. /// Detaches when the page is destroyed.
  20. ///
  21. protected override void OnDetachingFrom(Entry entry)
  22. {
  23. entry.TextChanged -= OnEntryTextChanged;
  24. base.OnDetachingFrom(entry);
  25. }
  26. private void OnEntryTextChanged(object sender, TextChangedEventArgs args)
  27. {
  28. if (!string.IsNullOrWhiteSpace(args.NewTextValue))
  29. {
  30. // If the new value is longer than the old value, the user is
  31. if (args.OldTextValue != null && args.NewTextValue.Length < args.OldTextValue.Length)
  32. return;
  33. var value = args.NewTextValue;
  34. if (value.Length == 3)
  35. {
  36. ((Entry)sender).Text += "-";
  37. return;
  38. }
  39. if (value.Length == 7)
  40. {
  41. ((Entry)sender).Text += "-";
  42. return;
  43. }
  44. ((Entry)sender).Text = args.NewTextValue;
  45. }
  46. }
  47. }
  48. }

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,