I have the following regex to match decimals:
@"[\d]{1,4}([.][\d]{1,2})?"
but I am able to input multiple decimal dots. How can I prevent this? In general, I can have input strings like "2000" or "2000.22". I have tried to use decimal.TryParse but I can input two decimal dots (e.g. 2000..)
Here is my class with method for validation:
public static class ValidationUtils
{
public static bool IsValid(string text)
{
var regex = new Regex(@"^\d{1,9}([.]\d{1,2})?$");
var success = regex.IsMatch(text);
return success;
}
}
Here is the call in page's code-begind:
private void OnPreviewTextInput(object sender, TextCompositionEventArgs eventArgs)
{
var box = eventArgs.OriginalSource as TextBox;
if (box == null) return;
eventArgs.Handled = !ValidationUtils.IsValid(box.Text + eventArgs.Text);
}
And the xaml of TextBox:
<TextBox Text="{Binding Nominal, Mode=TwoWay,
StringFormat={}{0:0.######}, UpdateSourceTrigger=PropertyChanged,
NotifyOnValidationError=True, ValidatesOnDataErrors=True,
Converter={StaticResource decimalValueConverter}}"
PreviewTextInput="OnPreviewTextInput"/>
Am I use a wrong event here?
Thanks you.