当用户在textbox1和textbox2中键入无效字符时,将出现“无效字符消息”,并且textbox1的文本变为红色

问题描述

我想进行一些无效的字符检测,就像我们在某些在线网站或移动应用程序中看到的那样。我使用WPF(.NET Framework)和C#代码

下面是我的textBox1用户输入)和textBox2无效的字符检测器)的XAML代码

请注意,我使用的是Material Design主题

<StackPanel VerticalAlignment="Center" Margin="10,20,10,30">
    <TextBox Name="CreatedsqlDatabase"
             BorderBrush="Black" 
             materialDesign:HintAssist.Hint="Add New Database Name"
             Style="{StaticResource MaterialDesignFloatingHintTextBox}" 
             Margin="0,0"
             FontFamily="Champagne &amp; Limousines" 
             FontSize="12"
             MaxLength="25"
             KeyDown="OnKeyDownHandler"/>
</StackPanel>
    <TextBox Name="InvalidCharacterDetection"
             materialDesign:HintAssist.Hint="Invalid character"
             Style="{StaticResource MaterialDesignFloatingHintTextBox}" 
             Margin="10,100,40"
             FontFamily="Champagne &amp; Limousines" 
             FontSize="12"
             MaxLength="25"
             IsReadOnly="True"/>

下面是无效字符事件处理程序检测器的C#代码

private void OnKeyDownHandler(object sender,KeyEventArgs e)
{
    var regex = new Regex(@"[^a-zA-Z0-9-()/\s\p{IsGreekandcoptic}]");

    if (regex.IsMatch(e.Key.ToString()))
    {
        InvalidCharacterDetection.Text = "You Entered an invalid character";
        CreatedsqlDatabase.Foreground = Brushes.Red;
    }
    else if (String.IsNullOrEmpty(CreatedsqlDatabase.Text))
    {
        InvalidCharacterDetection.Text = "Database name cannot be empty";
    }
    else if (CreatedsqlDatabase.Text.Length > 25)
    {
        InvalidCharacterDetection.Text = "Database name cannot exceed 25 characters";
    }
}

输出不正确(未应用任何正则表达式):

enter image description here

如何使KeyEvent处理程序捕获if语句,并对textBox1的颜色和出现在{{1}中的消息进行适当的更改}?

如果对此问题还有其他重复的问题,请在评论通知我。到目前为止,我发现了以下问题:

解决方法

我不知道正则表达式,但我想您想检查一下它是否(!)不匹配,不是吗?另外,尝试使用TextChanged代替KeyDown并验证CreatedSQLDatabase.Text的当前值:

private void OnTextChanged(object sender,TextChangedEventArgs e)
{
    var regex = new Regex(@"...");

    if (!regex.IsMatch(CreatedSQLDatabase.Text))
    {
        InvalidCharacterDetection.Text = "You Entered an invalid character";
        CreatedSQLDatabase.Foreground = Brushes.Red;
    }
    else if (string.IsNullOrEmpty(CreatedSQLDatabase.Text))
    {
        InvalidCharacterDetection.Text = "Database name cannot be empty";
    }
    else if (CreatedSQLDatabase.Text.Length > 25)
    {
        InvalidCharacterDetection.Text = "Database name cannot exceed 25 characters";
    }
    else
    {
        CreatedSQLDatabase.Foreground = Brushes.Black;
        InvalidCharacterDetection.Text = "The database name is valid";
    }
}