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

539 views Asked by At

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

2

There are 2 answers

0
Swati Chandra On BEST ANSWER

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>
0
Guangyu Bai - MSFT On

You can use the NumericValidationBehavior to determine if text input is a valid numeric value.

Here is the demo you can refer to:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="CommunityToolkit.Maui.Sample.Pages.Behaviors.NumericValidationBehaviorPage">


    <Entry Keyboard="Numeric">
        <Entry.Behaviors>
            <toolkit:NumericValidationBehavior 
                Flags="ValidateOnValueChanged"
                MinimumValue="1.0"
                MaximumValue="100.0"
                MaximumDecimalPlaces="2" />
        </Entry.Behaviors>
    </Entry>

</ContentPage>