I am struggling to apply a filter on a TexBox. I have 3 filter types:
1) Only Numbers (positive)
Example: 123 good, -123, ad8, 12.0 not good
2) Only Numbers plus "^" and "." chars
Example: 123^3, -34, -34.5 good, ad8, 23-4 not good
3) Only POSITIVE Numbers plus "^" and "." chars
Example: 123^3, 34.5 good, -34, ad8, 23-4 not good
Here is my work:
private void PriceInput_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
switch (FieldType)
{
case InputFieldType.TypeQuantity:
tb.Text = KeyFilter.ExtractNumbersOnly(tb.Text);
break;
case InputFieldType.TypePositivePrice:
tb.Text = KeyFilter.ExtractPositivePricesOnly(tb.Text);
break;
case InputFieldType.TypePrice:
tb.Text = KeyFilter.ExtractPricesOnly(tb.Text);
break;
}
}
and KeyFilter:
public static string ExtractNumbersOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "\\d+");
return match.Value;
}
public static string ExtractPricesOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "^[-]?\\d+([.]\\d+)?$");
return match.Value;
}
public static string ExtractPositivePricesOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "^[+]?\\d+([.]\\d+)?$");
return match.Value;
}
^(?:[-]?\\d+(?:[.]\\d+)?)(?:\^[-]?\\d+(?:[.]\\d+)?)?$and^(?:\\d+(?:[.]\\d+)?)(?:\^[-]?\\d+(?:[.]\\d+)?)?$respectively. This allows for things like-5.5^1.25and5.5^-1.25respectively.