0

I want to restrict a textbox to accept numbers from 1 to 4 and contain dot (.) also in C#. How do I do that?

2 Answers2

0

You could bind the KeyPress event to the textbox and then add your validation with regex, as described here: How to block or restrict special characters from textbox

Community
  • 1
  • 1
casaout
  • 1,819
  • 3
  • 24
  • 54
0

You may use this code snippet below in your software. The property is purely handled from codebehind, you may attach it in the XAML section as a textbox property.

PreviewTextInput is checking input characters on key press, so it won't allow invalid characters. In the Regex the allowed characters are defined.

XAML part:

Code Behind part

...
NumberRestrictFunction();
...

public void NumberRestrictFunction()
{
    textBox.PreviewTextInput += new TextCompositionEventHandler(MyNumbers_PreviewTextInput);
}

public static void MyNumbers_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = CheckIfMyCharacters(e.Text);
}

public static bool CheckIfMyCharacters(String text)
{
    Regex regex = new Regex(@"[1-4.]+");  
    return !regex.IsMatch(text);
}
Daniel
  • 126
  • 1
  • 12