I am trying to make a Numeric only TextBox in WPF and I have this code for it:
void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsValidInput(e.Text);
}
private bool IsValidInput(string p)
{
switch (this.Type)
{
case NumericTextBoxType.Float:
return Regex.Match(p, "^[0-9]*[.][0-9]*$").Success;
case NumericTextBoxType.Integer:
default:
return Regex.Match(p, "^[0-9]*$").Success;
}
}
// And also this!
public enum NumericTextBoxType
{
Integer = 0,
Float = 1
}
When I set the type to Integer, it works well, but for Float, it does not.
I can use so many NumericTextBox controls out there, but I was wondering why this one is not working?
Try this:
You need to escape the period. And making the period and decimal part optional is probably a good idea.
If you need to handle negative values you can add
-?before the first[0-9]in each pattern.Update
Tested as follows:
results in