Igo*_*r S 3 c# regex validation decimal
我有以下正则表达式来匹配小数:
@"[\d]{1,4}([.][\d]{1,2})?"
Run Code Online (Sandbox Code Playgroud)
但我可以输入多个小数点。我怎样才能防止这种情况发生?一般来说,我可以输入“2000”或“2000.22”等字符串。我尝试使用decimal.TryParse,但我可以输入两个小数点(例如2000..)
这是我的类,其中包含验证方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是页面代码开始中的调用:
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);
}
Run Code Online (Sandbox Code Playgroud)
以及 TextBox 的 xaml:
<TextBox Text="{Binding Nominal, Mode=TwoWay,
StringFormat={}{0:0.######}, UpdateSourceTrigger=PropertyChanged,
NotifyOnValidationError=True, ValidatesOnDataErrors=True,
Converter={StaticResource decimalValueConverter}}"
PreviewTextInput="OnPreviewTextInput"/>
Run Code Online (Sandbox Code Playgroud)
我在这里使用了错误的事件吗?
感谢您。
您需要锚定您的正则表达式。
@"^\d{1,4}([.]\d{1,2})?$"
Run Code Online (Sandbox Code Playgroud)
^匹配字符串的开头
$匹配字符串的结尾
如果你不这样做,你将得到部分匹配。