How to validate RichTextbox in WPF?

790 views Asked by At

How to validate RichTextbox in WPF? I want to validate the text for email and email separator i.e. emails should be entered with a semicolon.

Xaml:

              <StackPanel Orientation="Horizontal">                     
                <RichTextBox x:Name="txtEmail" Style="{StaticResource ContentRichTextBox}"
                             ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="0,0,10,0">
                    <FlowDocument>
                        <Paragraph LineHeight="5"></Paragraph>
                    </FlowDocument >
                </RichTextBox>
            </StackPanel>
            <StackPanel HorizontalAlignment="Center">
                <TextBlock x:Name="txterrormessage" Width="300" Foreground="#FFE5572C" FontSize="14" Visibility="Hidden" TextWrapping="Wrap"></TextBlock>
            </StackPanel>
            <StackPanel HorizontalAlignment="Center" Margin="60,0,0,0">
                <Button x:Name="BtnEmail" Style="{StaticResource ShortButtonStyle}" Content="NEXT" Margin="10" Command="{Binding CommandChanged}" CommandParameter="PROJECTS" Click="BtnEmail_Click"/>
            </StackPanel>

This is my code:

private void BtnEmail_Click(object sender, RoutedEventArgs e)
    {
        string richText = new TextRange(txtEmail.Document.ContentStart, txtEmail.Document.ContentEnd).Text;

        if (!Regex.IsMatch(richText, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
        {
            txterrormessage.Text = "Enter a valid email";
            txterrormessage.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            txterrormessage.Visibility = System.Windows.Visibility.Hidden;
        }

        if (!Regex.IsMatch(richText, @"^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;]{0,1}\s*)+$"))
        {
            txterrormessage.Text = "Separate emails with ;";
            txterrormessage.Visibility = System.Windows.Visibility.Visible;
        }
}

The code doesnt seem to work....How to validate?

Thanks

2

There are 2 answers

3
Barracoder On BEST ANSWER

The simplest way I've seen to do this is

    private void OnVerifyEmail()
    { 
       var recipients = richText.Split(';', StringSplitOptions.RemoveEmptyEntries);
       var validator = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
       foreach (var recipient in recipients)
       {
          var isValid = validator.IsValid(recipient.Trim());
          if(!isValid)
          {
             // do your thing here
          }
       }
    }
0
Bahman_Aries On

format your richText before validation:

richText = Regex.Replace(richText, @"(\n|\r)", "", RegexOptions.Multiline);

Edit:

This is the whole method and probably what you're looking for:

    private void BtnEmail_Click(object sender, RoutedEventArgs e)
    {
        string richText = new TextRange(txtEmail.Document.ContentStart, txtEmail.Document.ContentEnd).Text;
        richText = Regex.Replace(richText, @"(\n|\r)", "", RegexOptions.Multiline);
        richText = Regex.Replace(richText, @"( ;|; )", ";", RegexOptions.Multiline);
        txterrormessage.Visibility = System.Windows.Visibility.Hidden;

        if (!Regex.IsMatch(richText, @"^[\W]*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4}[\W]*,{1}[\W]*)*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4})[\W]*$"))
        {
            string[] emails = Regex.Split(richText, ";", RegexOptions.Multiline);
            foreach (string item in emails)
            {
                if (string.IsNullOrEmpty(item))
                    continue;

                if (!Regex.IsMatch(item, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
                {
                    txterrormessage.Text = item + " is not a valid email address";
                    txterrormessage.Visibility = System.Windows.Visibility.Visible;
                    break;
                }
            }
            if (string.IsNullOrEmpty(txterrormessage.Text))
            {
                txterrormessage.Text = "Separate emails with ; ";
                txterrormessage.Visibility = System.Windows.Visibility.Visible;
            }
        }
    }