Search code examples
c#mauinumeric-input

.NET MAUI Entry to accept only whole value greater or equal to 0


I am trying to write an Entry that will allow a user to enter only whole numbers greater then 0. Anything I tried is not working or working partially or acting strange (for example after pressing a dot then enter two numbers, the second one goes before the first one). I tried to do some "magic" in the TextChanged event without any luck and in Unfocused event. Any idea how this should be done? I need this for Android only, but it is welcome for iOS, too.

thnx


Solution

  • You can add a custom behavior in entry to allow only whole numbers. If any other character is pressed from keyboard, it will get ignored.

    Here is a sample example.

    1. Create a custom entry behavior.
    public class WholeNumberValidationBehavior : Behavior<Entry>
    {
        protected override void OnAttachedTo(Entry bindable)
        {
            bindable.TextChanged += Bindable_TextChanged;
            base.OnAttachedTo(bindable);
        }
    
        protected override void OnDetachingFrom(Entry bindable)
        {
            bindable.TextChanged -= Bindable_TextChanged;
            base.OnDetachingFrom(bindable);
        }
    
        private void Bindable_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.NewTextValue))
            {
                bool isWholeNumber = int.TryParse(e.NewTextValue, out int value) && value > 0;
                if (!isWholeNumber)
                {
                    ((Entry)sender).Text = e.OldTextValue;
                }
            }
            else
            {
                ((Entry)sender).Text = null;
            }
        }
    }
    

    You can play around with the conditions to allow special characters like dot or comma.

    1. Add this behavior in the xaml
    <Entry>
       <Entry.Behaviors>
          <behaviors:WholeNumberValidationBehavior/>
       </Entry.Behaviors>
    </Entry>