c# - WPF 文本框中正则表达式的用户输入验证

标签 c# regex wpf validation user-input

我有一组输入验证。 数组的每一行代表一个输入验证;一个正则表达式检查字符串和一个在验证失败时向用户显示的字符串:

public class myClass
{
     public static string[][] inputsInfo = new string[4][];

     static myClass()
     {
     // ID - 9 digits
     inputsInfo[0] = new string[2] { "^[0-9]{9}$", "exactly 9 digits (0-9)" };

     // only letters and possibly more than one word
     inputsInfo[1] = new string[2] { "^[A-Za-z]{2,}(( )[A-Za-z]{2,})*$", "only letters (A-Z) or (a-z)" };

     // Number - unlimited digits
     inputsInfo[2] = new string[2] { "^[0-9]+$", "only digits (0-9)" };

     // username, password
     inputsInfo[3] = new string[2] { "^[A-Za-z0-9]{6,}$", "at least 6 characters.\nOnly letters (A-Z) or (a-z) and digits (0-9) are allowed" };

     }
..............
..............
}

我有包含 WPF 文本框的窗口。有些字段具有相同的输入验证,这就是为什么我想将所有输入验证保存在数组中,所以我可以只选择我需要的验证。

我有这个表格:

...............

        <TextBlock Grid.Row="2" Grid.Column="0" Text="First name"/>
        <TextBox x:Name="firstName" Grid.Row="2" Grid.Column="1"/>
        <Button Grid.Row="2" Grid.Column="2" Content="Search"/>

        <TextBlock Grid.Row="3" Grid.Column="0" Text="Last name"/>
        <TextBox x:Name="lastName" Grid.Row="3" Grid.Column="1"/>
        <Button Grid.Row="3" Grid.Column="2" Content="Search"/>

        <TextBlock Grid.Row="4" Grid.Column="0" Text="ID number"/>
        <TextBox x:Name="ID" Grid.Row="4" Grid.Column="1"/>
        <Button Grid.Row="4" Grid.Column="2" Content="Search"/>

...............

每个文本框都有一个带有 Click 事件的附近按钮。 如何通过单击按钮执行输入验证?

有没有办法通过 XAML 代码做到这一点? 还是仅在 C# 代码的代码隐藏中?

我们将不胜感激。

最佳答案

How can i perform an input validation by a button click?

为什么不在 ViewModel 上创建 bool 标志来监视目标文本框的绑定(bind)文本属性以进行验证。示例

虚拟机:

public string FirstName { get { return _firstName; }
                          set { _firstname = value; 
                                PropertyChanged("IsFirstNameValid");
                                PropertyChanged("FirstName");
                              }
                        }

public bool IsFirstNameValid { get { return Regex.IsMatch( FirstName,
                                                           ValidationPatternFirstName); }}

XAML

<TextBox x:Name="firstName" 
         Text={Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

然后在对存储值 FirstName 进行任何更改时, bool 值 IsFirstNameValid 将在以后访问时准确反射(reflect)该状态。

您还可以绑定(bind)到屏幕上的 IsFirstNameValid 以显示或不显示图标,它会根据其状态进行更新。

关于c# - WPF 文本框中正则表达式的用户输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30448632/

相关文章:

c# - 自动递增数字的最佳实践 EF Core

javascript - 在 JavaScript 中从序列化 JSON 对象中提取变量

WPF 触发器绑定(bind)到 MVVM 属性

c# - 无法从 ListView 中的文本框中获取文本

c# - WPF 切角元素

c# - 列名不能为空

c# - Roslyn 的新版本 (Microsoft.CodeAnalysis) 中的 `Solution.LoadStandAloneProject` 发生了什么?

c# - 如何显示二次公式的解

java - 我将如何在 ColdFusion(或 Java)中实现这个正则表达式?

python - 如何在正则表达式中使用 'lookaround' 和字符时捕获整个字符串?