How to set an entry in .net maui to only except numbers?

SCRIEHL 1 Reputation point
2024-01-06T01:02:20.59+00:00

How can i set an entry in .net maui to only except numbers?

Developer technologies | .NET | .NET MAUI
{count} votes

2 answers

Sort by: Most helpful
  1. Justin Burcaw 5 Reputation points
    2024-07-05T04:08:37.4066667+00:00

    Here is the best solution. The previous solution has a problem with infinite looping but I was able to figure out how to correct the error!

    // Method triggered by TextChanged.
    private void Entry_TextChanged(object sender, TextChangedEventArgs e)
    {
    	// If the text field is empty or null then leave.
    	string regex = e.NewTextValue;
    	if (String.IsNullOrEmpty(regex))
    		return;
     
    	// If the text field only contains numbers then leave.
    	if (!Regex.Match(regex, "^[0-9]+$").Success)
    	{
    		// This returns to the previous valid state.
    		var entry = sender as Entry;
    		entry.Text = (string.IsNullOrEmpty(e.OldTextValue))?
    				string.Empty: e.OldTextValue;
    	}
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2024-01-08T02:42:11.2766667+00:00

    Hello,

    In MAUI, you could mask the number inputting by detecting the text.

    Please refer to the following sample code and documentation.

    <Entry TextChanged="Entry_TextChanged"/>
    
    private void Entry_TextChanged(object sender, TextChangedEventArgs e)
    {
        //Regular expressions are used to match whether the user input contains numbers
        string result = System.Text.RegularExpressions.Regex.Replace(e.NewTextValue, @"[^0-9]+", "");
        if (Regex.Match(result, @"^[0-9]+$").Success)
        {
            var entry = sender as Entry;
            if (e.OldTextValue == null)
            {
                entry.Text = string.Empty;
            }
            else
            {
                entry.Text = e.OldTextValue;
            }
    
        }
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.