XamaWIN – Entry Length Validation Behavior

Xamawin • zam-ah win | noun
A quick, easy to implement enhancement for a Xamarin App that improves performance, appearance, or functionality

Behaviors are super easy to make and offer a lot of bang for your buck – here’s a small example of a behavior I used recently to highlight incomplete/invalid user entry fields:

    public class EntryLengthValidator : Behavior<Entry>
        public int MaxLength { get; set; }
		public int MinLength { get; set; } = 0;

		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 is longer than valid length
			if (entry.Text.Length > this.MaxLength)
				string entryText = entry.Text;

				entryText = entryText.Remove(entryText.Length - 1); // remove last char

				entry.Text = entryText;

			if (MinLength > 0)
				if (entry.Text.Length < this.MinLength)
					((Entry)sender).TextColor = Color.Red;
					((Entry)sender).TextColor = Color.Black;

Notice that the minimum length is optional, but the max length is not – we trim any additional input after reaching the max character limit. Don’t forget to define your namespace first before adding the behavior to any entry field:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
<!-- More stuff -->
                <Label Text="Zip Code:" AbsoluteLayout.LayoutBounds="0,20,.3,40" AbsoluteLayout.LayoutFlags="WidthProportional" />
                <Entry Text="{Binding ZipCode}" AbsoluteLayout.LayoutBounds="1,10,.75,40" AbsoluteLayout.LayoutFlags="XProportional,WidthProportional">
                        <behaviors:EntryLengthValidatorBehavior MaxLength="10" MinLength="5"/>
<!-- More behaviors -->

The result looks like this:

Aug-07-2017 16-28-17

We could also attach other behaviors to validate Zip Codes specifically (potentially including any input masking and format validation), but I wanted to keep the length validator generic enough for almost any field.


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 )

Twitter picture

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

Facebook photo

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

Connecting to %s