Xamarin.Tips – Restrict the Length of Your Entry Text

Here’s a quick one on how to restrict the number of characters a user can enter in an Entry. Basically, we are going to create a custom Behavior and then apply it to our Entry.


 /// <summary>
    /// Behavior that restricts the length of an entry
    /// </summary>
    public class EntryLengthValidatorBehavior : Behavior<Entry>
        public int MaxLength { get; set; }

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

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

        void OnEntryTextChanged(object sender, TextChangedEventArgs e)
            var entry = (Entry)sender;

            if (entry.Text.Length > this.MaxLength)
                string entryText = entry.Text;
                entry.TextChanged -= OnEntryTextChanged;
                entry.Text = e.OldTextValue;
                entry.TextChanged += OnEntryTextChanged;

Now we can apply it in our Xaml:

<Entry x:Name="Pin1" TextColor="White">
        <behaviors:EntryLengthValidatorBehavior MaxLength="4"/>

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!


3 thoughts on “Xamarin.Tips – Restrict the Length of Your Entry Text”

  1. great issues altogether, you just gained a new reader.
    What could you recommend about your post that you simply made a few
    days in the past? Any positive?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s