Search code examples
c#wpftextbox

When user types invalid characters in textbox1 and in textbox2 an "invalid character message" is appeared and the textbox1's text is made red


I would like to make a fancy invalid character detection , like the one we see in some online websites or mobile applications. I use WPF (.NET Framework) and C# code.

Below is the XAML code of my textbox1 (user input) and textbox2 (invalid character detector).

Note that I use the Material Design themes.

<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,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,10,40"
             FontFamily="Champagne &amp; Limousines" 
             FontSize="12"
             MaxLength="25"
             IsReadOnly="True"/>

Below is the C# code of the invalid characters event handler detector :

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";
    }
}

The output is not correct (none of the regex expressions is applied):

enter image description here

How could I make the KeyEvent handler to catch the if statements and make the appropriate changes in the color of the textbox1 and the message that is appeared in the textbox2?

Please notify me in the comments if there is any other duplicate question regarding this one. I found the following questions So far :


Solution

  • I don't know about regular expression but I guess you want to check if it doesn't (!) match, don't you? Also, try TextChanged instead of KeyDown and validate the current value of 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";
        }
    }