0

I'm trying to restrict the first character other than English alphabet, but I'm still able to enter whitespace as first character which is not what I want. How can I prevent the first character from beeing a whitespace during the typing?

private void TbxCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z]$");

    if (tbxCode.Text.Length == 0)
    {
        if (!myRegex.IsMatch(e.Text))
        {
            e.Handled = true;
        }
    }
}

<Window x:Class="WpfApp"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cgmsui="clr-namespace:ClassGetMSUI;assembly=ClassGetMSUI">

        <Grid>
            <TextBox Name="tbxCode"
                     Width="100"
                     Height="20"
                     PreviewTextInput="TbxCodeHoraire_PreviewTextInput" />
        </Grid>
</Window>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

2 Answers2

0

if (tbxCode.Text.Length == 0) you're only handling the regex when there is nothing in the text box, you should change it to if (tbxCode.Text.Length != 0).

Also, your regex only allow a single character in the text box. If you want to validate only the fisrt character, it should be @"^[a-zA-Z]";

Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • I tried to change with your modifications but nothing happend. I still can add a whitespace as first character. – LaurentMts Jul 21 '22 at 11:32
0

Here is my solution

private void TbxCode_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z]$");
        if (e.Key == Key.Space)
        {
            if (tbxCode.Text.Length == 0)
            {
                if (!myRegex.IsMatch(e.Key.ToString()))
                {
                    e.Handled = true;
                }
            }
        }
    }

Thanks to this article : Why does PreviewTextInput not handle spaces?